【问题标题】:Django templates - Reusable fragment with flexible nameDjango 模板 - 具有灵活名称的可重用片段
【发布时间】:2011-12-18 15:27:52
【问题描述】:

我有一个可重复使用的 HTML 片段,用于列出项目。所以要在视图中列出项目,我只是这样做:

variables = RequestContext(request, {
    'items': items,
}
return render_to_response('template_in_question',variables)

片段是:

{% for item in items %}
    <p>Item: {{item.name}} </p>
{% endfor %}

到目前为止一切顺利。但是,有些视图我想两次使用相同的可重用片段。例如,如果我想列出最畅销的商品和最新的商品,我需要创建该可重用片段的两个副本:

视图会是这样的:

variables = RequestContext(request, {
    'most_sold_items': most_sold_items,
    'latest_items': latest_items
}

并且在 HTML 中需要有两个可重用的 HTML 模板:

{% for item in most_sold_items %}
     <p>Item: {{item.name}}</p>
{% endfor %}

还有第二个

 {% for item in latest_items %}
     <p>Item: {{item.name}}</p>
 {% endfor %}

所以我的问题是:如何在同一个视图中使用两个或多个项目列表,并为此使用通用 HTML 模板?例如,在上面的视图中,传递“most_sold_items”和“latest_items”并以某种方式仅使用一个 HTML 模板来分别列出它们?

【问题讨论】:

    标签: django django-templates


    【解决方案1】:

    您可以使用包含标签来做到这一点。基本上,你最终会得到:

    <h1>Most sold items</h1>
    {% include "items.html" with items=most_sold_items only %}
    
    <h1>Latest items</h1>
    {% include "items.html" with items=latest_items only %}
    

    【讨论】:

    • 谢谢。这正是我想要的。
    猜你喜欢
    • 2013-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-21
    • 2016-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多