从模板中渲染 Django 模板

Rendering Django template from withing template

因此,我有许多要循环渲染的对象。 IE。在主页上呈现 5 个最新帖子中的每一个。无论用户是否登录,这些帖子中的每一个都会以不同的方式显示。

我有一个问题:我将如何进行区分?我想像这样的模板

{% if user.is_logged_in %}
    {% for post in latest_posts %}
        post.render_long_form
    {% endfor %}
{% else %}
    {% for post in latest_posts %}
        post.render_short_form
    {% endfor %}
{% endif %}

如何使函数 render_short_formrender_long_form return 成为合适的 HTML 片段?我希望他们调用其他模板进行底层渲染。

谢谢!

为什么不使用 {% include %} 标签?

{% if user.is_logged_in %}
    {% for post in latest_posts %}
        {% include 'long_form.html' %}
    {% endfor %}
{% else %}
    {% for post in latest_posts %}
        {% include 'short_form.html' %}
    {% endfor %}
{% endif %}

或者,更多 DRY 版本:

{% for post in latest_posts %}
    {% if user.is_logged_in %}
        {% include 'long_form.html' %}
    {% else %}
        {% include 'short_form.html' %}
    {% endif %}
{% endfor %}