custom template operator
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开发者_Python百科)
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.
精彩评论