【问题标题】:Put the result of simple tag into a variable将简单标签的结果放入变量中
【发布时间】:2015-11-17 20:46:39
【问题描述】:

这行得通:

{% get_option 'payment_conditions' '' true %}

它调用一个带有 3 个参数的函数并返回一个字符串:“我是条件”。太好了。

我现在要做的是把它放在一个 IF 语句中。所以要做到这一点,我需要将值转换为变量。比如:

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

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

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

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

【问题讨论】:

  • get_option是你定义的模板标签吗?
  • 是的,它已被定义并且在 IF 语句中起作用。

标签: python django django-templates templatetag


【解决方案1】:

如果您使用的是 django 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 语句。

同时引用文档:

1.9 版后已弃用:simple_tag 现在可以将结果存储在 模板变量,应改为使用。

【讨论】:

  • assignment_tag 已在 Django 2.0 中删除
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-21
相关资源
最近更新 更多