Reputation: 3163
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
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
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
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