问题
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
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).
- 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