如何在Django模板中声明变量 [英] How to declare variables inside Django templates

查看:253
本文介绍了如何在Django模板中声明变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Django 1.8模板中声明变量,例如:

How do I declare a variable in Django 1.8 Templates for example like this:

{% my_var = "My String" %}

这样我就可以这样访问它:

And so that I can access it like this:

<h1>{% trans my_var %}</h1>

编辑:

为了说明我的目的,这是我的代码:

{% my_var = "String Text" %}

{% block meta_title %}{% trans my_var %}{% endblock %}

{% block breadcrumb_menu %}
{{ block.super }}
<li>{% trans my_var %}</li>
{% endblock %}

{% block main %}

<h1>{% trans my_var %}</h1>


推荐答案

尝试使用with标记。

Try using the with tag.

{% with my_var="my string" %}
{% endwith %}

对于您要尝试执行的操作,其他答案更正确,但这对于更普通的情况会更好。

The other answer is more correct for what you're trying to do, but this is better for more generic cases.

仅来自问题标题的人将需要此。

Those who come here solely from the question title will need this.

这篇关于如何在Django模板中声明变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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