Django templates and DRY - how to avoid duplicate HTML

advertisements

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.

  • Pro: DRY-compliant
  • Con: makes code harder to read, specially if condition is more complex and several HTML element attributes are manipulated

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

  • Pro: DRY-compliant
  • Con: move logic to client-side

Suggestions are welcome.


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.