views:

30

answers:

1

Is it possible?

I know about filters, but is it possible to create something like this:

{% if 75 is_divisible_by 5 %}

It just looks a lot nicer than:

{% if 75|is_divisible_by:5 %}

(this is a concept question, is_divisible_by is just an example)

A: 

No, there isn't a way to do what you are asking.

(Caution: tangential) If however you only wanted to render the value of is_divisible_by 75 5 you could define a custom template tag. Something like this:

@register.tag('is_divisible_by')
def is_divisible_by(_parser, token):
    try:
        _tag_name, dividend, divisor = token.split_contents()
    except ValueError:
        raise template.TemplateSyntaxError, \ 
            "%r tag requires exactly two arguments" % token.contents.split()[0]

    return IsDivisibleBynode(dividend, divisor)

class IsDivisibleBynode(template.Node):
    def __init__(self, dividend, divisor):
        self.dividend = template.Variable(dividend)
        self.divisor = template.Variable(divisor)

    def render(self, context):
        return (int(self.dividend.literal)  % int(self.divisor.literal) == 0)

This could then be used in a template like this:

<p>{% is_divisible_by 75 5 %}</p>

Of course this will only print True which is not what you need. I couldn't find a way of combining this with an if condition. Perhaps someone with better template tag fu can tell us how to do it.

Manoj Govindan
Yeah, I see now that the only way (afaik) is to rewrite the if tag. People have done this alreadywith the "smart if" tag http://djangosnippets.org/snippets/1350/It looks like it could be modified to add is_divisible_by operator. I'll give it a try.
Cek