【问题标题】:How to avoid repetition on templates in Django? [duplicate]如何避免 Django 中的模板重复? [复制]
【发布时间】:2017-08-05 08:42:45
【问题描述】:

我在多个模板上重复了以下代码:

{% for element in elements %}
    <div class="some-class">
        <div class="another-class">
            <div class="row">
                <div class="col-xs-3">
                    <img class="img-responsive" alt="{{ entry.user }} avatar" style="border-radius: 50%; width: 100%;" src="{{ entry.avatar_url}}">
                </div>
                <div class="col-xs-9" style="some-style">
                    {% if entry.data1 %}<small>{% trans entry.data1 %}</small><br>{% endif %}
                    {% trans entry.data2 %} {% trans entry.data2 %}
                    <br>
                    <small style="some-style">
                        {% blocktrans with timestamp=entry.timestamp|naturaltime %}
                            {{ timestamp }}
                         {% endblocktrans %}
                    </small>
                 </div>
            </div>
        </div>
    </div>
{% endfor %}

我想知道避免重复这段代码的最佳方法是什么,我是 Django 的新手,非常感谢您的帮助。

编辑: 如果我需要将内容传递给该模板怎么办。它会使用与包含文件中的上下文相同的上下文,还是应该以某种方式指示上下文?

【问题讨论】:

    标签: python django django-templates


    【解决方案1】:

    这很简单:

    将这段 HTML 放入一个名为 reusable.html 的文件中,然后将 include 放入其他模板中。

    像这样:

    <!-- Other HTML -->
    
    ... html stuff here
    
    {% include 'reusable.html' %}
    

    现在,如果你想向reusable.html 传递一个参数,你可以这样做:

    `{% include 'reusable.hmtl' with var_a='abc' var_b=123 %}`
    

    【讨论】:

    • 哦,是的。就是这么简单。我一直这样做。让我保持干爽;)
    • 如果我需要将参数传递给该模板怎么办?或者上下文是否与包含的文件中的上下文相同?
    • 更新了我的答案!
    • 还有一个问题,我应该重新加载新文件中的{% load i18n %} 和其他加载还是包含文件中的加载就足够了?
    • 是的,在每个模板中您必须包含{% load ... %}
    【解决方案2】:

    在它自己的模板中设置它,例如new_template.html 并在任何你想要的地方使用{% include 'new_template.html' %}

    【讨论】:

    • 谢谢你,虽然你的答案和另一个很相似。
    猜你喜欢
    • 2014-05-15
    • 2015-02-19
    • 2011-08-02
    • 2011-03-04
    • 1970-01-01
    • 2023-03-22
    • 1970-01-01
    • 2023-03-09
    • 1970-01-01
    相关资源
    最近更新 更多