如何在Django模板中干掉常见文本?

Thi*_*Lam 3 django django-templates

我有一些静态文本需要显示在模板中的2个位置.

例如:

<div>
{% if something %}
    This is a static text
{% else %}
    Something else happened
{% endif %}
</div>
... more html
<span>
{% if something %}
    This is a static text
{% else %}
    Something else happend
{% endif %}
</span>
Run Code Online (Sandbox Code Playgroud)
  1. 我可以通过在我的模板文件中的两个不同位置复制上述文本来完成上述操作(如上所示).
  2. 我还可以创建一个存储文本的模型(这是干的,但是为了一个简单的任务需要调用DB)
  3. 我正在考虑使用,include template但这可能不是实现我的目标的最佳方式.

最好的方法是什么?

Ada*_*son 7

绝对使用包含标签:

http://docs.djangoproject.com/en/dev/howto/custom-template-tags/#inclusion-tags

标签文件要么是超级简单的,就像文本"这是一个静态文本"或整个块一样:

{% if something %}
This is a static text
{% else %}
Something else happened
{% endif %}
Run Code Online (Sandbox Code Playgroud)

"something"可以作为变量传递给模板标记,因此您可以以可变的方式使用整个块.