【问题标题】:How to pass one django template with a 'for loop' into another one using 'include' statement?如何使用“包含”语句将一个带有“for循环”的django模板传递给另一个模板?
【发布时间】:2020-03-05 02:05:15
【问题描述】:

我正在处理常见问题解答页面,其中问题和答案根据其类别传递到模板部分。我想减少 html 的数量并使用部分 div 作为模板

<div id="{{id}}">
    <div class="h2">{{category}}</div>
    {% for q in faqs %}
        {% if q.category == '{{category}}' %}
        <ul class="collapsible">
            <li>
                <div class="collapsible-header">{{q.question}}></div>
                <div class="collapsible-body"><span>{{q.answer}}</span></div>
                <div class="divider"></div>
            </li>
        </ul>
        {% endif %}
    {% endfor %}
</div>

我的主 html 包含以下代码:

{% with id='m_faq'%}
{% with category='Methodology'%}
   {% include 'main/faqs_section.html' %}
{% endwith %}{% endwith %}

我只能传递变量 id 和类别。 有没有办法进入 for 循环?

【问题讨论】:

  • 您的问题并不完全清楚。你所说的 for 循环以及在哪个部分是什么意思?

标签: django templates django-templates


【解决方案1】:

我认为解决方案是在 views.py 中为类别创建一个列表

cat = [ 'Category1', 'Category2', 'Category3','Category4']

将其传递给上下文字典,然后在 div 部分周围放置额外的“for循环”。

{% for c in cat %}
<div id="">
    <div class="h4">{{c}}</div>
    {% for q in faqs %}
    {% if c == q.category %}
    <ul class="collapsible">
        <li>
            <div class="collapsible-header">{{q.question}}</div>
            <div class="collapsible-body"><span>{{q.answer}}</span></div>
            <div class="divider"></div>
        </li>
    </ul>
    {% endif %}
    {% endfor %}
</div>
{% endfor %}

这将生成一个模板,其中包含分为多个部分的常见问题解答列表..

【讨论】:

    猜你喜欢
    • 2018-02-02
    • 2018-05-25
    • 1970-01-01
    • 1970-01-01
    • 2012-08-15
    • 1970-01-01
    • 2018-09-10
    • 2012-08-24
    • 1970-01-01
    相关资源
    最近更新 更多