Django CMS -检查占位符是否为空

mv1qrgav  于 2023-10-21  发布在  Go
关注(0)|答案(7)|浏览(146)

我用途:

  • DjangoCMS 2.4
  • Django 1.5
  • Python 2.7.3

我想检查一下我的占位符是否为空。

<div>
    {% placeholder "my_placeholder" or %}
    {% endplaceholder %}
</div>

如果占位符为空,我不希望创建占位符之间的html。

{% if placeholder "my_placeholder" %}
<div>
    {% placeholder "my_placeholder" or %}
    {% endplaceholder %}
</div>
{% endif %}
igsr9ssn

igsr9ssn1#

如果您希望在占位符为空的情况下显示其他内容,请使用or参数和附加的{% endplaceholder %}结束标记。如果占位符没有插件或插件不生成任何输出,则呈现{% placeholder "..." or %}{% endplaceholder %}之间的所有内容。
范例:

{% placeholder "content" or %}

There is no content.

{% endplaceholder %}
pftdvrlh

pftdvrlh2#

这里有一个非常紧凑的解决方案。
模板过滤器:

@register.filter('placeholder_is_empty')
def placeholder_is_empty(request, slot):
    page = request.current_page
    placeholder = page.placeholders.get(slot=slot)
    return placeholder.cmsplugin_set.exists()

模板中的用法:

{% if request|placeholder_is_empty:'myplaceholder' %}
    <h1>Here comes some content... </h1>
{% endif %}
wb1gzix0

wb1gzix03#

根据您尝试实现的目标,如果没有内容,您可以使用:empty选择器简单地使用CSS隐藏元素。如果你担心白色空格,你可以使用Django的内置模板标签{% spaceless %}来删除它们。
你会得到这个模板:

{% spaceless %}
<div class="hide_if_empty">
    {% placeholder "my_placeholder" %}
</div>
{% endspaceless %}

这个CSS:

hide_if_empty:empty {
    display: none;
}

不完全是什么要求,因为它不删除HTML -但这将解决最常见的情况下,一个人想检查如果一个地方保持器是空的,并不需要引入一个新的模板标记。

olhwl3o2

olhwl3o24#

2023更新

https://stackoverflow.com/a/17148137/5322302与最新的DjangoCMS有问题。
更新的解决方案(F.B. DjangoCMS社区)。
使用Django CMS 4进行测试。

{% load get_placeholder %}
...
{% get_placeholder "content" as placeholder_content %}
{% if placeholder_content %}
    <div class="my-2">{{ placeholder_content }}</div>
{% endif %}

模板标签的代码.../templatetags/get_placeholder.py

from classytags.arguments import Argument, MultiValueArgument
from classytags.values import StringValue
from django import template
from django.utils.safestring import mark_safe

from cms.models.placeholdermodel import Placeholder as PlaceholderModel
from cms.templatetags.cms_tags import (
    DeclaredPlaceholder,
    Placeholder,
    PlaceholderOptions,
)

register = template.Library()

class RenderGetPlaceholder(Placeholder):
    """
    Render the content of a placeholder to a variable. Can be provided
    with the name of the placholder (i.e. "Header" in the case of a normal
    CMS page) or a template variable containing a placeholder (i.e. myentry.content in the
    case of an external app using a placeholder)

    {% get_placeholder ["string"|placeholder_var] as variable_name %}

    e.g.
    {% load extra_cms_tags %}
    {% get_placeholder "My Placeholder" as my_placeholder %}

    {% if my_placeholder %}
    <div>
        {{ my_placeholder }}
    </div>
    {% endif %}
    """

    name = "get_placeholder"

    options = PlaceholderOptions(
        Argument("name", resolve=True),
        MultiValueArgument("extra_bits", required=False, resolve=False),
        "as",
        Argument("varname", resolve=False, required=True),
        blocks=[
            ("endplaceholder", "nodelist"),
        ],
    )

    def render_tag(self, context, name, extra_bits, varname, nodelist=None):
        if isinstance(name, PlaceholderModel):
            content = name.render(context, None)
        else:
            content = super(RenderGetPlaceholder, self).render_tag(context, name, extra_bits, nodelist)
        context[varname] = mark_safe(content)
        return ""

    def get_declaration(self):
        # Fix some template voodoo causing errors
        slot = self.kwargs["name"].var.var.__str__().strip('"').strip("'")

        return DeclaredPlaceholder(slot=slot, inherit=False)

register.tag(RenderGetPlaceholder)
bihw5rsg

bihw5rsg5#

基于@Philip Zedler的伟大答案表单,这是一个既适用于django-cms页面上的占位符,也适用于“cms之外”的占位符的解决方案。

@register.filter()
def placeholder_empty(page_placeholder, slot=None):
    """
    for page/slot, pass a page object, and a slot name:  
    {% if request.current_page|djangocms_misc_placeholder_empty:"content" %}

    for a outside page placeholder, just the placeholder object:
    {% if object.placeholderfield|djangocms_misc_placeholder_empty %}

    also, with:
    {% with ph_empty=object.placeholderfield|djangocms_misc_placeholder_empty %}
    """
    placeholder = None
    if isinstance(page_placeholder, Placeholder):
        placeholder = page_placeholder
    elif isinstance(page_placeholder, Page):
        page = page_placeholder
        try:
            placeholder = page.placeholders.get(slot=slot)
        except Placeholder.DoesNotExist:
            pass
    if placeholder:
        # // return not placeholder.cmsplugin_set.filter(language=get_language()).exists()
        return not placeholder.cmsplugin_set.exists()
    return False

模板中的用法

{% if request.current_page|placeholder_empty:'content' %}
    <h1>Fallback!</h1>
{% endif %}

在我的djangocms-misc包里

vddsk6oq

vddsk6oq6#

我采用了额外的紧凑型解决方案here,并创建了一个templatetag,用于检查static占位符是否为空:

from cms.toolbar.utils import get_toolbar_from_request

@register.filter("static_placeholder_is_not_empty")
def static_placeholder_is_not_empty(request, slot):

    placeholder = StaticPlaceholder.objects.get(code=slot)

    if get_toolbar_from_request(request).edit_mode_active:
        placeholder = placeholder.draft
    else:
        placeholder = placeholder.public

    is_not_empty = len(placeholder.get_plugins(request.LANGUAGE_CODE)) > 0
    return is_not_empty

它的用法是这样的:

{% load my_new_shiny_templatetag %}

{% if request|static_placeholder_is_not_empty:'my_static_placeholder' %}
  <div class="something">
{% endif %}

{% static_placeholder "my_static_placeholder" %}

{% if request|static_placeholder_is_not_empty:'my_static_placeholder' %}
  </div>
{% endif %}
nkoocmlb

nkoocmlb7#

目前在django-cms中还没有内置的方法来做到这一点,所以你必须编写一个自定义模板标签。在django-cms Google Group上有一些关于这个问题的旧讨论:

  • https://groups.google.com/forum/#!topic/django-cms/WDUjIpSc23c/discussion
  • https://groups.google.com/forum/#!msg/django-cms/iAuZmft5JNw/yPl8NwOtQW4J
  • https://groups.google.com/forum/?fromgroups=#!主题/django-cms/QeTlmxQnn 3E
  • https://groups.google.com/forum/#!topic/django-cms/2 mWvEpTH 0 ns/讨论

基于第一次讨论中的代码,我整理了以下要点:

我是这样用的:

{% load extra_cms_tags %}
{% get_placeholder "My Placeholder" as my_placeholder %}

{% if my_placeholder %}
<div>
    {{ my_placeholder }}
</div>
{% endif %}

相关问题