this quick question, think may limitation in templates.
i'm adding value variable in template using |add:"num" feature, i'm trying use variable number doesn't seem work. should possible ?
e.g.
{{ pagecontrol.start_page|add:"-pagecontrol.news_per_page" }} thanks in advance all.
wayne
django not provide built-in template tag/filter subtraction. also, there no built-in filter converting positive integer negative. have write template tag that.
solution 1- use custom template filter:
@register.filter def subtract(value, arg): return value - arg then in template, can like:
{{ pagecontrol.start_page|subtract:pagecontrol.news_per_page }} solution 2- use django-mathfilters library
you can use django-mathfilters library subtract filter.
first, load mathfilters @ top of template. use sub filter in template below:
{% load mathfilters %} {{ pagecontrol.start_page|sub:pagecontrol.news_per_page }} why code not working?
django source code of add built-in filter:
@register.filter(is_safe=false) def add(value, arg): """adds arg value.""" try: return int(value) + int(arg) except (valueerror, typeerror): try: return value + arg except exception: return '' when {{ pagecontrol.start_page|add:"-pagecontrol.news_per_page" }} in template, '-pagecontrol.news_per_page' string passed arg above add built-in filter , not actual value, exception raised because of adding integer , string values. '' returned final value add filter nothing displayed.
note:
in case of complex variables name, can use with template tag. cache complex variable under simpler name.
below sample example of using with add filter. add values.
{% my_variable=pagecontrol.news_per_page %} this store value of pagecontrol.news_per_page in variable my_variable. in template, can use variable:
{{ pagecontrol.start_page|add:my_variable }} this add 2 variables.
{% my_variable=pagecontrol.news_per_page %} {{ pagecontrol.start_page|add:my_variable }} {% endwith %}
Comments
Post a Comment