简体   繁体   中英

Django CMS – Show different content for users and guests in same template

I would like to have different content for users and guests in my home page's template using Django 1.9 and Django CMS 3.3.1 .

It could be acomplished by making subpages and showing the corresponding content in the ancestor based on authentication conditional, but that makes the page structure overly complicated.

Is there an easy way of adding these placeholders straight to the template ?

I have tried this:

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

But as I am authenticated when I'm editing the content, I cannot access the guests placeholder.

Try this:

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

I have some experience with Django CMS but don't know if this will work. The idea is to check if we're in edit mode by inspecting corresponding request variables. See this answer .


Update by @V-Kopio:

The answer given above works fine in practice but Django warns about dublicate placeholders. This can be avoided by combining the if and else blocks:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM