【问题标题】:Django CMS – Show different content for users and guests in same templateDjango CMS – 在同一模板中为用户和访客显示不同的内容
【发布时间】:2016-12-04 03:18:18
【问题描述】:

我希望使用 Django 1.9Django 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 占位符。

【问题讨论】:

    标签: python django django-templates django-cms


    【解决方案1】:

    试试这个:

    {% 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 %}
    

    【讨论】:

    • 你拯救了我的一天。实际的一半已经消失了。但是,非常感谢。
    猜你喜欢
    • 2014-08-31
    • 2018-10-11
    • 1970-01-01
    • 2019-06-07
    • 1970-01-01
    • 2017-09-19
    • 2023-03-08
    • 1970-01-01
    • 2016-11-30
    相关资源
    最近更新 更多