在{%if%}块中为自定义模板标记提供参数的语法 [英] Syntax to supply a parameter to a custom template tag in {% if %} block

查看:276
本文介绍了在{%if%}块中为自定义模板标记提供参数的语法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经设置了一个自定义模板标签(simple_tag)(使用 https://stackoverflow.com/a/7716141/1369798),其定义如下:

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" %}

但这只是插入文本进入我的HTML输出。

But this just inserts the text into my HTML output.

在{%if%}中使用参数的模板标签是什么语法?

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 %}


推荐答案

使用模板标签作为另一个模板标签的参数。您的选项是

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


  1. 修改 settings_value templatetag,以便它可以注意当前上下文中的值,例如:

  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%}
您被允许。
{%endif%}

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

请注意, simple_tag 不会在这里工作,你将不得不切换到 assignement_tag (如果你的Django版本支持它) - 但是你会失去直接输出的能力在模板中设置一个实际的方式 - 或者写一个完整的自定义模板(这并不像最初看起来那么困难)。

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. 使用自定义的context_processor,而不是像danhip建议的那样,但是只有使用 RequestContext 呈现的模板才能访问这些变量。

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

这篇关于在{%if%}块中为自定义模板标记提供参数的语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆