模板是否可以在{%if%}和{%else%}方案中保留一个块

时间:2014-07-09 12:20:43

标签: django django-templates django-cms

我有一个定义了条件头的基本模板:

{% if blah %}
    <h1>Title 1</h1>
{% else %}
    <h1>Title 2</h1>
{% endif %}

模板中是否有可用的技术/功能,您可以在从基础扩展的模板中设置标题?

显然你不能使用传统的块标签,因为它们只能出现一次,但你可以做些什么来有效地为每个{% block title %}实现<h1>,以便从中提取任何标题扩展模板更改了if

更具体地说,我在基地获得的模板代码是;

<div class="wrapper">
    {% if request.current_page.get_ancestors|length <= 1 %}
        {% block page_title %}
        <h1>{{ request.current_page.get_page_title }}</h1>
        {% endblock page_title %}
    {% else %}
        {% for ance in request.current_page.get_ancestors %}
            {% if ance.level == 1 %}
            {% block page_title %}
                <h1>{{ ance.get_page_title }}</h1>
            {% endblock page_title %}
            {% endif %}
        {% endfor %}
    {% endif %}
</div>

修改

基本模板的完整代码; http://pastebin.com/cyWAiWn2

扩展模板的完整代码; http://pastebin.com/ThEqff47

这个功能要求的原因是在django-cms中我创建了一个页面并将我的应用程序挂钩到该页面。在那个阶段{{ request.current_page.get_page_title }}将返回我创建的django-cms页面的标题。

如果您在该页面上做了某些事情,使得挂钩的应用程序将您发送到另一个视图/模板,那么您实际上并未在django-cms中更改页面,因此get_page_title仍然是相同的,但模板你现在渲染的几乎总会有不同的标题。

显然,您可以将新页面标题包含为<h2>或其他任何内容,并将其放在<h1> base_content.html下面,但基本标题通常是多余的水平。

1 个答案:

答案 0 :(得分:0)

如果你只有一个这样的标题栏,那么你可以在扩展模板中使用普通的块标签来覆盖标题。

<div class="wrapper">
    {% block title %}
        {% if request.current_page.get_ancestors|length <= 1 %}
            <h1>{{ request.current_page.get_page_title }}</h1>
        {% else %}
            {% for ance in request.current_page.get_ancestors %}
                {% if ance.level == 1 %}
                    <h1>{{ ance.get_page_title }}</h1>
                {% endif %}
            {% endfor %}
        {% endif %}
    {% endblock title %}
</div>

我没有看到你的模板中需要两个标题栏,你能提供一个需要定义两个标题栏的重写模板的例子吗?