views:

1074

answers:

2

name class an id, a first & a last attributes

In my view.py, I fetch a name object from the database and pass it into the index.html template.

In my templagetags/my_tags.py, I have a filter my_private_tag(value, arg) that takes value and an arg. It appends the arg to the value and returns the result.

def my_private_tag(value, arg):
  return value + ' ' + arg

In my index.html tag I need to do the following.

{% if name %}

  # to display 
  # John says hello
  {{name.first | my_private_tag:"says hello"}

  # Johns student id = id_value
  {{name.first | my_private_tag:"????????"}

  # Johns student id = id_value, lastname = lastname_value
  {{name.first | my_private_tag:"????????"}

{% endif %}

Where:

id_value = name.id & lastname_value = name.last

Please fill in the ???????? if you can.

+7  A: 

Instead of implementing your own filter for this. Why not do it this way:

{{name.first }} says hello
{{name.first }}'s student id = {{ name.id }}

It is much more readable. And this is how you are supposed to use templates anyway.

If you still want to use a custom filter for this, you can probably pass the variable like this:

{{name.first|my_private_tag:name.id}}
Nadia Alramli
Thanks Nadia,Well, I put a simple example to figure out how to do this.The real filter will do more stuff on the input.And for your information, this just doesn't work. {{name.first | my_private_tag:name.id}}. Thanks.
VN44CA
I removed the spaces between the filter and the arguments. Apparently django doesn't like that. The new example worked for me.
Nadia Alramli
Thanks Nadia, Do you know how to make this work:{{name.first|my_private_tag:studend_id=name.id}}. Something like named argument.
VN44CA
A: 

If the filter only gets two strings, it won't have access to the original name object, so there's no way to get the ID.

I think you're headed the wrong direction by wanting to do this with a filter when you can use the existing tags to get the result you want. But, for the sake of argument, let's say that you could get

Johns student id = 47, lastname = Doe

from the filter. How would you do it? First, you'd have to pass the name object to the filter

{{name|my_private_tag:"??????"}}

The code for the filter then becomes

return name.first_name + "s student id = " + name.id + ", lastname = " + name.last_name

Notice that you're not using the argument. If you wanted your filter to return different things depending on the argument, then add conditional logic and off you go.

Dave W. Smith