benzkji
benzkji

Reputation: 1867

Link to a page in django cms, first check if it exists

I often do things like this in a django template, with django-cms:

{% load cms_tags %}
<a href="{% page_url 'imprint' %}">Imprint</a>

On production, this fails silently, and the href attribute is empty. On development, I'm forced to insert the page with id "imprint", otherwise I get a "DoesNotExist" exception.

How can I improve this situation? Maybe I'm looking for something like

{% if 'imprint'|cms_page_exists %}
    ...the link and stuff...

Is there a known best practice for this (not quite seldom) use case? Or do you all use it as shown first?

Upvotes: 2

Views: 2455

Answers (1)

Alex Morozov
Alex Morozov

Reputation: 5993

You could assign a tag result to a variable and then check is it empty:

{% page_url 'imprint' as url %}
{% if url %}
    <a href="{{ url }}">Imprint</a>
{% endif %}

Other ways imply creating your own template tag or filters, so the above is the simplest one IMHO. See also an example in the docs.

Upvotes: 5

Related Questions