Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/351.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何在Django模板中使用模板?_Python_Html_Django_Templates_Django 1.4 - Fatal编程技术网

Python 如何在Django模板中使用模板?

Python 如何在Django模板中使用模板?,python,html,django,templates,django-1.4,Python,Html,Django,Templates,Django 1.4,我有django模板,如下所示: <a href="https://example.com/url{{ mylist.0.id }}" target="_blank"><h1 class="title">{{ mylist.0.title }}</h1></a> <p> {{ mylist.0.text|truncatewords:50 }}<br> ... 实际的模板相当大 应在同一页面上使用10次,但“外部”html元

我有django模板,如下所示:

<a href="https://example.com/url{{ mylist.0.id }}" target="_blank"><h1 class="title">{{ mylist.0.title }}</h1></a>
<p>
{{ mylist.0.text|truncatewords:50 }}<br>
...
实际的模板相当大

应在同一页面上使用10次,但“外部”html元素不同:

<div class="row">
  <div class="col-md-12 col-lg-12 block block-color-1">
    *django template here - mylist.0, truncatewords:50 *
  </div>
</div>

<div class="row">
  <div class="col-md-4 col-lg-4 block block-color-2">
    *django template here - mylist.1, truncatewords:15 *
  </div>
  <div class="col-md-8 col-lg-8 block block-color-3">
    *django template here - mylist.2, truncatewords:30 *
  </div>
</div>
...
看起来,在考虑第一个、最后一个、奇数个和偶数个元素的情况下偶数使用for不会简化任务


如何使开头给出的模板只定义一次?

您可以使用include标记。它是内置标签的一部分:


如果您需要做更复杂的事情,您可以编写自己的模板标记:

您可以使用include标记。它是内置标签的一部分:

如果需要执行更复杂的操作,您可以始终编写自己的模板标记:

您可以使用标记为包含的模板提供一致的变量名:

例如:

parent.html

更新:按照spectras的建议,您可以在标记中使用with和only关键字,以便为包含的模板提供必要的上下文。

您可以使用标记,以便为包含的模板提供一致的变量名称:

例如:

parent.html


更新:按照spectras的建议,您可以在标记中使用with和only关键字,以便为包含的模板提供必要的上下文。

您是否尝试过{%include%}@Wtower,我不确定如何使用包含,因为应使用不同的列表元素,请参见mylist.0、mylist.1等以及不同的TRUNCTEWORD值50,15和30。你试过{%include%}@Wtower吗?我不知道如何使用include,因为应该使用不同的列表元素。请参见mylist.0、mylist.1等以及不同的truncatewords值50、15和30。以这种方式使用with标记是一个聪明的主意+实际上,我认为这样做要好得多:{%include'templates/child.html'with list_item=mylist.0t=50 only%}这使得模板可以访问给定的变量,唯一的关键字隐藏了所有其他内容。最好是子模板不访问父上下文,以便重用和封装。这是一个非常好的@spectras,从未注意到这一点。更新,谢谢。以这种方式使用with标记是一个聪明的主意+实际上,我认为这样做要好得多:{%include'templates/child.html'with list_item=mylist.0t=50 only%}这使得模板可以访问给定的变量,唯一的关键字隐藏了所有其他内容。最好是子模板不访问父上下文,以便重用和封装。这是一个非常好的@spectras,从未注意到这一点。更新,谢谢。
<div class="row">
    <div class="col-md-12 col-lg-12 block block-color-1">
        {% include 'templates/child.html' with list_item=mylist.0 t=50 only %}
    </div>
</div>
{{ list_item.text|truncatewords:t }}