Django CMS - 在同一模板中为用户和访客显示不同的内容

时间:2016-07-29 11:57:17

标签: python django django-templates django-cms

我希望使用 Django 1.9 Django CMS 3.3.1 在我的主页模板中为用户和访客提供不同的内容。

可以通过制作子页面并根据身份验证条件在祖先中显示相应的内容来实现,但这会使页面结构过于复杂。

是否可以轻松地将这些占位符直接添加到模板

我试过这个:

{% extends "base.html" %}
{% load cms_tags %}

{% block title %}{% page_attribute "page_title" %}{% endblock title %}

{% block content %}
    {% if not user.is_authenticated %}
        {% placeholder "guests" %}
    {% endif %}

    {% if user.is_authenticated %}
        {% placeholder "authenticated" %}
    {% endif %}

    {% placeholder "content" %}
{% endblock content %}

但是当我在编辑内容时进行身份验证时,我无法访问guests占位符。

1 个答案:

答案 0 :(得分:4)

试试这个:

{% block content %}
    {% if request.toolbar.build_mode or request.toolbar.edit_mode %}

        {% placeholder "guests" %}
        {% placeholder "authenticated" %}

    {% else %}

        {% if not user.is_authenticated %}
            {% placeholder "guests" %}
        {% endif %}

        {% if user.is_authenticated %}
            {% placeholder "authenticated" %}
        {% endif %}

    {% endif %}

    {% placeholder "content" %}
{% endblock content %}

我对Django CMS有一些经验,但不知道这是否有效。我们的想法是通过检查相应的请求变量来检查我们是否处于编辑模式。请参阅this answer

@ V-Kopio更新:

上面给出的答案在实践中运作良好,但Django警告有关共和国的占位符。通过组合ifelse块可以避免这种情况:

{% block content %}

    {% if not user.is_authenticated or request.toolbar.build_mode or request.toolbar.edit_mode %}
        {% placeholder "guests" %}
    {% endif %}

    {% if user.is_authenticated %}
        {% placeholder "authenticated" %}
    {% endif %}

    {% placeholder "content" %}
{% endblock content %}
相关问题