python - 将简单标记的结果放入变量中

标签 python django django-templates templatetag

这个有效:

{% get_option 'payment_conditions' '' true %}

它调用一个带有 3 个参数的函数并返回一个字符串:“I am the conditions”。太好了。

我现在要做的是把它放在一个 IF 语句中。所以要做到这一点,我需要将值放入一个变量中。像这样的东西:

{% with conditions = get_option 'payment_conditions' '' true %}

但它不起作用。我也试过:

{% get_option 'payment_conditions' '' true as conditions %}

有没有办法可以将结果放入变量? 谢谢

最佳答案

如果您使用的是 django < 1.9,请使用赋值标签。文档是 here .我在此处的文档中发布了示例:

@register.assignment_tag
def get_current_time(format_string):
    return datetime.datetime.now().strftime(format_string)

然后在模板中:

{% get_current_time "%Y-%m-%d %I:%M %p" as the_time %}
<p>The time is {{ the_time }}.</p>

使用as语句可以看到模板标签结果变成了一个变量。您可以随心所欲地使用 the_time,包括 if 语句。

另请参阅文档:

Deprecated since version 1.9: simple_tag can now store results in a template variable and should be used instead.

关于python - 将简单标记的结果放入变量中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32182116/

相关文章:

python - Lambda、可调用类实例和作用域;为什么它在 Python 2.7 中不起作用?

python - 正则表达式在 bs4 中不起作用

python - 根据最后一个 LARGEST 值替换数据框中当前值的最快方法

python - 当我在另一个模板中包含一个模板时,如何传递源文件的路径?

python - Django URL 调度程序示例 - 将 url 从 View 传递到另一个 View

python - 如何捕捉 LightGBM 训练进度

python - 无法执行 collectstatic

python - 将密码字段迁移到 Django

python - 将 ValidationError 提升为字典时出错

django - 如何在django中创建密码输入字段