简体   繁体   中英

Python web frameworks: HTML server-side templates and duplication of code

I'm experimenting Python web frameworks and HTML templates. The concept seems restricted, compared to generating entire HTML code on the fly. For instance, to generate a combo box, I found the following Django templating example:

<select id="{{ item.name }}" name="{{ item.name }}">
{% for choice in item.choices %}
  {% ifequal item.value choice %}
  <option value="{{ choice }}" selected>{{ choice }}</A>
  {% else %}
  <option value="{{ choice }}">{{ choice }}</A>
  {% endifequal %}
{% endfor %}
</select>

The ifequal statement duplicates entire code just to add a "selected" attribute to the selected option. It seems to me this becomes a burden in HTML tags with several attributes and which some few attributes exist or not depending on a condition. Is the above snippet a bad usage of templating? Is there a better way to implement the combo box using it?

这样可以将其写在一行中。

<option value="{{ choice }}" {% ifequal item.value choice %}selected="selected"{% endifequal %}>{{ choice }}</option>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM