【问题标题】:django reusing html block for different for loop in the same templatedjango 为同一模板中的不同 for 循环重用 html 块
【发布时间】:2013-04-26 09:09:14
【问题描述】:

我对给定对象有三个条件,1。开始2。开始3。完成。 我过滤视图本身中的对象并将三个变量发送到模板 - tostart_objectsstarted_objectsfinished_objects

现在我循环遍历html模板中的三个for循环如下:

{% for obj in tostart_objects %}
// chunk of html template to display all the object 
{% endfor %}

{% for obj in started_objects %}
// similar chunk of html template as above
{% endfor %}

{% for obj in finished_objects %}
// similar chunk of html template as above
{% endfor %}

我可以不在三个不同的地方重用它们,而不是放置相同的代码块吗? 如何才能做到这一点?请告知,谢谢!

【问题讨论】:

    标签: python html django django-templates


    【解决方案1】:

    这样做的一种方法是将 HTML 块放在单独的模板文件中,并使用{% include %} 将其包含在每个循环中。在此基础上,您可以将整个循环定义为包含模板标记,该标记将对象列表作为参数。

    或者,您可以连接视图中的三个列表,然后循环遍历结果。

    【讨论】:

    • +1 template tag 文档参考
    • 这当然是一种解决方法,但 Django 模板系统中仍然缺少一个功能。如果我只在一个模板中使用它,为什么还要依赖另一个文件?为什么我不能一次看到所有代码,最好是在第一次使用的地方?
    猜你喜欢
    • 1970-01-01
    • 2020-10-14
    • 2017-09-13
    • 2021-10-17
    • 2012-07-25
    • 1970-01-01
    • 1970-01-01
    • 2021-09-04
    • 1970-01-01
    相关资源
    最近更新 更多