【问题标题】:Is there any way to reuse template tag value in Django templates?有没有办法在 Django 模板中重用模板标签值?
【发布时间】:2011-03-27 05:20:42
【问题描述】:

例如,假设有一个自定义模板标签

{% custom_tag "parameter" %}

这个标签需要一些严肃的数据库工作来计算。

现在我需要类似的东西(伪代码):

if {% custom_tag "parameter" %} 
....
else
....

我知道使用上下文变量我可以做到:

{% with variable.x.y.z as v %}
 {% if v %}
  Blah-Blah-Blah {{ v }}
 {% else %}
  No value
 {% endif %}
{% endwith %}

但是有没有什么办法可以用模板标签值来实现呢?

编辑: 到目前为止,我想出的唯一选择是从我的模板标签中制作一个过滤器:

{% if "parameter" | custom_tag %}
 Blah {{ "parameter" | custom_tag }}
{% else %}
 ....
{% endif %}

但是这个选项会使 custom_tag 执行两次,这在性能方面并不好

【问题讨论】:

    标签: django django-templates


    【解决方案1】:

    我还没有测试它,但我想你可以从你的自定义标签中添加一个变量到上下文中。也许这会对你有所帮助 http://docs.djangoproject.com/en/dev/howto/custom-template-tags/#setting-a-variable-in-the-context

    【讨论】:

    • 不幸的是,我必须使用带有参数的模板标签,所以我不能真正为此创建上下文变量:(
    • 好吧,我仍然认为您的答案在我发布的链接中,如果您查看他们的示例,他们还会将参数传递给自定义标签,最后他们会创建一个可以使用的变量在模板的其余部分。所以我想你可以这样做: {% custom_tag "parameter" %} {% if response %} bla bla {% else %} bla bla 假设“response”是在自定义标签上创建的变量
    • 感谢您的想法。我已经定义了在其中设置上下文变量的自定义标签。以 django 模板/defaulttags.py 中的“do_with”为例。
    【解决方案2】:

    我相信您可以将过滤结果分配给一个变量并使用它。这样过滤器将only get called once。来自文档:with:以更简单的名称缓存复杂变量。这在多次访问“昂贵”方法(例如,访问数据库的方法)时很有用。

    {% with "parameter" | custom_tag as result %}
    {% if result %}
        Blah {{ result }}
    {% else %}
        ....
    {% endif %}
    {% endwith %}
    

    【讨论】:

      猜你喜欢
      • 2021-06-04
      • 2022-01-05
      • 2014-03-20
      • 2014-02-26
      • 2011-03-28
      • 1970-01-01
      • 2012-12-02
      • 1970-01-01
      • 2015-03-18
      相关资源
      最近更新 更多