【问题标题】:Is django can modify variable value in template?django 可以修改模板中的变量值吗?
【发布时间】:2015-11-02 04:21:29
【问题描述】:

我想写一个只渲染一次的模板。

我的想法是创建一个标志变量来检查它是否是第一次。

我的代码

{% with "true" as data %}
    {% if data == "true" %}
        //do something
        ** set data to "false" **
    {% else %}
        //do something
    {% endif %}
{% endwith %}

我不知道如何更改django模板中的变量。可以吗?或者有更好的方法吗?

【问题讨论】:

  • 您是否尝试通过 for 循环 (forloop.first) 执行此操作?你想达到什么目标?
  • @Sayse 谢谢这个解决方案可以解决我的问题

标签: django django-templates


【解决方案1】:

这可以通过 Django 自定义过滤器来完成

django custom filter

def update_variable(value):
    data = value
    return data

register.filter('update_variable', update_variable)

{% with "true" as data %}
    {% if data == "true" %}
        //do somethings
        {{update_variable|value_that_you_want}}
    {% else %}
        //do somethings
    {% endif %}
{% endwith %}

【讨论】:

  • 谢谢,但是是否有另一种方法可以通过不使用自定义标签或自定义过滤器来更改变量值?
  • 模板应该只包含渲染逻辑,在 django 视图中完成所有这些计算。
  • with 语句会更好。见stackoverflow.com/questions/11324839/…
  • 如果我不想打印那个变量怎么办?
【解决方案2】:

NIKHIL RANE 的回答对我不起作用。自定义simple_tag() 可以用来做这项工作:

@register.simple_tag
def update_variable(value):
    """Allows to update existing variable in template"""
    return value

然后像这样使用它:

{% with True as flag %}
    {% if flag %}
        //do somethings
        {% update_variable False as flag %}
    {% else %}
        //do somethings
    {% endif %}
{% endwith %}

【讨论】:

    猜你喜欢
    • 2016-10-31
    • 1970-01-01
    • 1970-01-01
    • 2012-07-20
    • 2012-02-17
    • 1970-01-01
    • 1970-01-01
    • 2021-11-01
    • 1970-01-01
    相关资源
    最近更新 更多