utapyngo
utapyngo

Reputation: 7136

Conditional link in Django templates

Is there a DRY shorthand for the following Django template code?

{% if condition %}
  <a href="{% url 'url_name' arg1 arg2 kwarg='some value' %}">
    {# just some block of code #}
    <h2>{{ value|capfirst }}</h2>
  </a>
{% else %}
  {# the same block of code #}
  <h2>{{ value|capfirst }}</h2>
{% endif %}

Upvotes: 2

Views: 1362

Answers (2)

Burhan Khalid
Burhan Khalid

Reputation: 174614

Personally, I don't see something non-DRY in your code (readability trumps DRY in my opinion).

However if you must, you can create a template tag that renders your links based on the content of the condition variable. In your tag though, you'd have the same if-loop logic. It would just move the code from your template to the tag. I would caution against this though, as it is just adding complexity for vanity (in my opinion). Plus, template tags/filters are difficult to debug.

You could also decide to build the links in your view code, but again, you are going to have to write the same type of logic structure (if-statement).

Perhaps someone would suggest using javascript to modify the node based on the flag but again - simplicity and readability trumps everything else.

Remember, you'll have to maintain this code sometime down the line. As a code golf exercise this is a good one, though.

Upvotes: 2

user764357
user764357

Reputation:

If you need to keep your HTML structure, this is probably the most readable way.

{% if condition %}
  <a href="{% url 'url_name' arg1 arg2 kwarg='some value' %}">
{% endif %}
    <h2>Heading</h2>
{% if condition %}
  </a>
{% endif %}

Upvotes: 1

Related Questions