django template filter ,use 2 or more filter like pipe

谁都会走 提交于 2019-12-12 13:28:18

问题


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


回答1:


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) 



回答2:


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.



来源:https://stackoverflow.com/questions/10427193/django-template-filter-use-2-or-more-filter-like-pipe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!