Question

I want to use more than one filter on template like below:

value: {{ record.status|cut:"build:"|add:"5" }}

where record.status would be build:n, 0 < n< 100 but I want to add this value a base value 5.

I tried above code, it only take effect on the first filter, so I did not get the value plus 5.

Does django only support one filter? Thanks

Was it helpful?

Solution

First, the answer for your question "Does django only support one filter?" is that Django does support almost unlimited number of chained filters (depends on your platform and ability to write that number of chained filters of course =) . Take some code for example (not proof but it makes sense), it is actually a template '{{ x|add:1|add:1|...10000 in all...|add:1 }}'

>>> from django.template import *
>>> t = Template('{{ x|'+'|'.join(['add:1']*10000)+' }}')
>>> t.render(Context({'x':0}))
u'10000'

Second, please check the template to ensure that you are using built-in version of cut and add; also check the output value after the cut to ensure it can be coerced to int w/o raising exception.
I've just checked and found that even the Django 0.95 supports this usage:

def add(value, arg):
    "Adds the arg to the value"
    return int(value) + int(arg) 

OTHER TIPS

Chaining filters is supported. If you want to figure why it doesn't work, then what I'd do is:

  1. install ipdb
  2. in django/templates/defaultfilters.py, find "def add", and put "import ipdb; ipdb.set_trace()" at the top of the function
  3. open the page in the browser again, you should be able to follow the execution of the code from the terminal that runs runserver and figure why you're not getting the expected results

An easier way is to make your own template filter. It could look like

from django.template import Library

register = Library()

@register.filter
def cut_and_add(value, cut, add):
    value = value.replace(cut, '')
    value = int(value) + add
    return value

Suppose you saved this in yourapp/templatetags/your_templatetags.py (and that yourapp/templatetags/__init__.py exists - it can be empty). Then you would use it in the template as such:

{% load your_templatetags %}

{{ record.status|cut_and_add:"build:",5 }}

Of course, this is untested, pseudo code. But with a little effort you could get it to work.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top