If you're using a combination of Bootstrap.css and Django's template engine
{% if param.status == 1 %}
<!--Give the class name active for certain conditions-->
<li class="active">
{% else %}
<li>
{% endif %}
<a href="#">Active</a>
</li>
……
There are times when you have to write like this. Indentation gets confusing and It's hard to see how many lines are spent on just this much processing.
So I tried to find out how to write it short. I found a built-in filter called "yesno". https://docs.djangoproject.com/en/dev/ref/templates/builtins/?from=olddocs#yesno
This filter takes a comma-separated string as an argument. If the value can be interpreted as True, from the beginning of the argument to the comma, If the value can be interpreted as False, then the first and second commas, And if the value is None, it will return from the second comma. (None is optional)
{{ value|yesno "Yes,No,None" }}
given that, When the value is True (example: "1", "hoge", etc. are OK), "Yes", When the value is False (example: "0" "" "]), it is" No ".
If you rewrite the above template with this interesting filter
<!--Give the class name active for certain conditions-->
<li class="{{ param.status|yesno:'active,' }}">
<a href="#">Active</a>
</li>
It will be. One line will be longer, but than the previous writing The structure of the indent is refreshing and easy to see, which is a great advantage.
Recommended Posts