Alan Evangelista
Alan Evangelista

Reputation: 3163

Django templates and DRY - how to avoid duplicated HTML

I have recently started to use Django templates and I've often found the following pattern in others' code:

  {% ifequal value 1 %}
      <input type="checkbox" name="{{ item.name }}" id="{{ item.name }}" checked="checked" />
  {% else %}
      <input type="checkbox" name="{{ item.name }}" id="{{ item.name }}"  />

Conditions with Django template variables are being used to define the value of one or more HTML element attributes. This duplicates HTML code and breaks DRY principle. How could I avoid that?

Alternatives I have considered:

1) embed the condition in the checked attribute.

2) Define Javascript variables using the template variable values and generate HTML elements with Javascript.

Suggestions are welcome.

Upvotes: 2

Views: 1069

Answers (3)

Dr.Elch
Dr.Elch

Reputation: 2225

As a third option you can use your view to control the checked="checked" part.

Make a pseudo field called e.g. "checked" that is attached to each of your items and will hold either an empty string (not None) or checked="checked" based on the fact if value is 1 or not, or whatever your condition will be.

You will allow you to write:

<input type="checkbox" name="{{ item.name }}" id="{{ item.name }}" {{ item.checked }}  />

This applies to the DRY principe and it is still explicit. Although this will be shifted to your view.

Upvotes: 0

rdegges
rdegges

Reputation: 33844

In your example, you can simplify things quite a bit (see below):

<input type="checkbox" name="{{ item.name }}" id="{{ item.name }}" {% ifequal value 1 %}checked="checked"{% endif %} />

As you can see, there's no need to duplicate the code here -- you can embed your if statement inside the HTML to save text.

Upvotes: 1

dannymilsom
dannymilsom

Reputation: 2406

I don't think there is anything wrong with that snippet. It might break some DRY but the code is ultimately very readable and maintainable.

Two core philosophies from the Zen of Python are

Explicit is better than implicit

and

Readability counts

Generating HTML via JavaScript is definitely not explicit, while putting conditions inside a element affect readability.

Upvotes: 2

Related Questions