【问题标题】:Django Templates - Changing context for an 'include' templateDjango 模板 - 更改“包含”模板的上下文
【发布时间】:2011-01-07 20:48:58
【问题描述】:

我有一个包含多个表格的模板。我想使用一个以相同方式呈现这些表格的子模板。通过在视图中设置上下文并将其传递给模板,我可以让它适用于单个表。但是如何更改数据以针对不同的数据呈现另一个表?

**'myview.py'**

from django.shortcuts import render_to_response
table_header = ("First Title", "Second Title")
table_data = (("Line1","Data01","Data02"),
              ("Line2","Data03","Data03"))
return render_to_response('mytemplate.html',locals())

**'mytemplate.html'**

{% extends "base.html" %}
{% block content %}
<h2>Table 01</h2>
{% include 'default_table.html' %}
{% endblock %}

**'default_table.htm'**

<table width=97%>
<tr>
{% for title in table_header %}
<th>{{title}}</th>
{% endfor %}
</tr>
{% for row in table_data %}
<tr class="{% cycle 'row-b' 'row-a' %}">
{% for data in row %}
<td>{{ data }}</td>
{% endfor %}
</tr>
{% endfor %}
</table>

如果我在“myview.py”中添加更多数据,您将如何传递它以便“default_table.html”可以呈现第二组数据?

(对不起...我刚开始使用 Django)

行政长官

【问题讨论】:

    标签: django include django-templates


    【解决方案1】:

    您可以在include 中使用with

    {% include "default_table.html" with table_header=table_header1 table_data=table_data1 %}
    

    另见documentation on include tag

    【讨论】:

      【解决方案2】:

      你可以试试with template tag:

      {% with table_header1 as table_header %}
      {% with table_data1 as table_data %}
          {% include 'default_table.html' %}
      {% endwith %}
      {% endwith %}
      
      {% with table_header2 as table_header %}
      {% with table_data2 as table_data %}
          {% include 'default_table.html' %}
      {% endwith %}
      {% endwith %}
      

      但我不知道它是否有效,我自己没有尝试过。

      注意:如果您必须经常包含此内容,请考虑创建一个custom template tag

      【讨论】:

      • 自定义标签会更优雅,但我可以确认withinclude 标签可以这样协同工作。
      • 嘿菲利克斯。干杯。这样可行。这是我的第一个模板,所以至少我可以继续前进。但是你们都是对的,一旦我掌握了基础知识,我需要看看自定义模板标签。真的很感激。
      猜你喜欢
      • 2023-04-03
      • 1970-01-01
      • 1970-01-01
      • 2013-08-01
      • 1970-01-01
      • 2012-03-16
      • 1970-01-01
      • 2017-12-04
      • 2016-09-22
      相关资源
      最近更新 更多