Reputation: 210755
How do I pass the result of a tag to a filter in Django?
e.g.
{{ {% widthratio a b c %}|add: 2 }}
Upvotes: 2
Views: 1869
Reputation: 7070
Just use the "as" keyword:
{% widthratio a b c as result %} {{ result | add: 2 }}
Upvotes: 2
Reputation: 542
Here is my custom template tag solution:
from django import template
from django.template.defaulttags import WidthRatioNode
register = template.Library()
class WidthRationExtraNode(WidthRatioNode):
def render(self, context):
extra = int(self.extra.resolve(context))
value = int(super(WidthRationExtraNode, self).render(context))
return str(value+extra)
def __init__(self, val_expr, max_expr, max_width, extra):
self.extra = extra
super(WidthRationExtraNode, self).__init__(val_expr, max_expr, max_width)
def widthratioextra(parser, token):
bits = token.contents.split()
if len(bits) != 5:
raise TemplateSyntaxError("widthratio takes four arguments")
tag, this_value_expr, max_value_expr, max_width, extra = bits
return WidthRationExtraNode(parser.compile_filter(this_value_expr),
parser.compile_filter(max_value_expr),
parser.compile_filter(max_width),
parser.compile_filter(extra))
widthratioextra = register.tag(widthratioextra)
You can use it in your template:
{% widthratioextra a b c d %}
Adding custom template tags to your application is relatively easy, if you don't know how to do it, here is relevant part of the manual: https://docs.djangoproject.com/en/dev/howto/custom-template-tags/
Upvotes: 0
Reputation: 12318
The correct way to do this is to write your own tag:
{% widthratio_add a b c d %}
Where the tag you write does the same logic as widthratio, then adds the number to it.
Though, i suspect you're only trying to do this because django doesn't allow basic math in the template beyond "add", and by the time you are writing your own tag you could do something far more straightforward with fewer arguments:
{% mymathtag a d %}
Check out this for a general description of how to do this: Do math using Django template filter?
Upvotes: 0
Reputation: 129964
You cannot, unless the tag knows how to modify the context (those usually have xxx as variable
syntax available). If it doesn't, you can write a wrapper (as a custom tag) that will.
Upvotes: 2