Syntax to supply a parameter to a custom template tag in {% if %} block

喜夏-厌秋 提交于 2020-01-15 12:30:09

问题


I have setup a custom template tag (simple_tag) (using https://stackoverflow.com/a/7716141/1369798) with a definition like this:

templatetags/polls_extras.py

def settings_value(name)

which I am able to use in my template like this:

templates/index.html

{% settings_value "ALLOWED_BOOL" %}

But this just inserts the text into my HTML output.

What is the syntax to use my template tag with parameter in an {% if %}?

I tried this but I get the error: TemplateSyntaxError at / Unused '"ALLOWED_BOOL"' at end of if expression.

templates/index.html

{% if settings_value ALLOWED_BOOL %}
You are allowed.
{% endif %}

回答1:


You cannot use a templatetag as a parameter to another templatetag. Your options here are either

  1. modifying your settings_value templatetag so it can inject the value in the current context, ie :

    {% settings_value ALLOWED_BOOL as allowed_bool %} {% if allowed_bool %} You are allowed. {% endif %}

Note that simple_tag won't work here, you'll either have to switch to assignement_tag (if your Django version support it) - but then you'll loose the ability to directly output a setting in the template the way you actually do - or write a full blown custom templatetag (which is not as difficult as it might seem at first).

  1. Use a custom context_processor instead like danhip suggests - but then only templates rendered using a RequestContext will access these variables.


来源:https://stackoverflow.com/questions/25645219/syntax-to-supply-a-parameter-to-a-custom-template-tag-in-if-block

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