I use:
I would like to check if my placeholder is empty.
<div>
{% placeholder "my_placeholder" or %}
{% endplaceholder %}
</div>
I don't want the html between the placeholder to be created if the placeholder is empty.
{% if placeholder "my_placeholder" %}
<div>
{% placeholder "my_placeholder" or %}
{% endplaceholder %}
</div>
{% endif %}
Here's a very compact solution.
Template filter:
@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()
Usage in template:
{% if request|placeholder_is_empty:'myplaceholder' %}
<h1>Here comes some content... </h1>
{% endif %}
There is no built-in way to do this at the moment in django-cms, so you have to write a custom template tag. There are some old discussions about this on the django-cms
Google Group:
Based on the code in the first discussion, I've put together the following Gist:
I use it like so:
{% load extra_cms_tags %}
{% get_placeholder "My Placeholder" as my_placeholder %}
{% if my_placeholder %}
<div>
{{ my_placeholder }}
</div>
{% endif %}
Depending on what you are trying to achieve, you can simply use CSS to hide the element if doesn't have content using the :empty selector. And if you are worried about white spaces you can use Django's in-build {% spaceless %} template tag to remove them.
So you'd get this template:
{% spaceless %}
<div class="hide_if_empty">
{% placeholder "my_placeholder" %}
</div>
{% endspaceless %}
And this CSS:
hide_if_empty:empty {
display: none;
}
Not exactly what was asked for as it doesn't remove the HTML - but this will solve the most common case where one wants to check if a place holder is empty, and doesn't require the introduction of a new template tag.
If you want additional content to be displayed in case the placeholder is empty, use the or
argument and an additional {% endplaceholder %}
closing tag. Everything between {% placeholder "..." or %}
and {% endplaceholder %}
is rendered in the event that the placeholder has no plugins or the plugins do not generate any output.
Example:
{% placeholder "content" or %}
There is no content.
{% endplaceholder %}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With