Michal Ludvig wrote:

> for the project I'm working on I needed to create a custom template tag,
> call it 'mytag'.
> 
> If I use it as {% mytag something %} everything goes fine (where
> 'something' is a string passed to the template).
> However I can't add any filters to that 'something'. As soon as I do:
> {% mytag something|upper %}
> I get an exception:
>       VariableDoesNotExist at /test/
>       Failed lookup for key [something|upper]
> 
> That leads to a code in MytagNode.render() method:
>       actual_message = resolve_variable(self.message, context)
> where self.message is the argument passed to the macro, in this case
> it's a string 'something|upper'.
> 
> Is there an easy way to run all the attached filters in MytagNode?

For the record:
There is a FilterExpression class in django.template that does exactly 
what I need. So for the tag implementation, instead of:

===
from django.template import resolve_variable

@register.tag
def mytag(parser, token):
        tag_name, message = token.split_contents()
        [...]
        return MytagNode(message)

class MytagNode(template.Node):
        [...]
        def render(self, context):
                actual_message = resolve_variable(self.message, context)
                [...]
===

I do it like this:

===
from django.template import FilterExpression

@register.tag
def mytag(parser, token):
        [...]
        filter_expression = FilterExpression(message, parser)
        return MytagNode(filter_expression)

class MytagNode(template.Node):
        [...]
        def render(self, context):
                actual_message = self.filter_expression.resolve(context)
                [...]
===

The filter_expression.resolve(context) runs all the filters attached to 
the variable and things work as expected. The 'parser' argument even 
makes it aware of custom filters loaded through {% load ... %} tags.

Lesson learned, note taken.

Michal



--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to