django 可以修改模板中的变量值吗? [英] Is django can modify variable value in template?

查看:28
本文介绍了django 可以修改模板中的变量值吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to write a template that renders something only one time.

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

My idea is to create a flag variable to check it is the first time.

我的代码

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

我不知道 如何更改 django 模板中的变量. 可能吗?或者有没有更好的方法来做到这一点?

I don't know How to change a variable in django template. Is it possible? Or is there a better way to do this?

推荐答案

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

This can be done with a Django custom filter

django 自定义过滤器

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 可以修改模板中的变量值吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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