标记或继承 Django 模板中的相同代码,稍作更改

Tag or inherit the same code in Django template with minor changes

我有一堆代码需要在一个页面和多个页面上重复使用。例如,这是代码的较短版本:

<a href="#"
   data-toggle="popover"
   title="{% for terms in s_terms %}{% if terms.slug == 'neuron' %}{{terms.title}}{% endif %}{% endfor %}"
   data-content="{% for terms in s_terms %}{% if terms.slug == 'neuron' %}{{terms.para_one}}{% endif %}{% endfor %}">
  Toggle popover
</a>

块中有更多代码。现在,出于显而易见的原因,我不想继续重复这么大块的代码。我是 DRY 方法的粉丝。

但是,我不知道如何重复呈现同一段代码。唯一会改变的是那里的单词 = "neuron" 。我想过使用模板标签,但是没有用。

我尝试将代码另存为一个单独的文件,并在我的模板中继承它,但我无法更改关键字 ('neuron')。我还尝试创建一个单独的动态页面,并将其包含在我的 Django 模板中,但看起来 include 标记只适用于模板,而不适用于动态页面。

有人可以帮忙吗?提前谢谢你。

您可以使用 Django 模板内置的模板标签 include

来自文档:

Loads a template and renders it with the current context. This is a way of “including” other templates within a template.

因此,您只需将代码段提取到单独的模板中,然后将其用于:

{% include "snippet_template.html" %}

此外,您可以使用 with 关键字将变量传递给包含模板 - 您可以使用它来传递 word 参数:

{% include "snippet_template.html" with word="neuron" %}

正如@bonidjukic 所写,include 语句就是您搜索的内容。

但是 for-loop 中的 include 语句可能会触及 Django 模板引擎(相对于 Jinja)的一个弱点。你只包含变量,所以它会很快。

在需要标签的情况下(如trans),Django 将在每次包含时加载标签。 Jinja 所在的地方会有 global "tags".

因此,请小心处理模板的方式。