我有一个模板基本代码,如下所示。模板将注入模型 主题 中的内容。现在, topic.div_element 包含在 views.py views.py中使用外部(由地图生成)生成的div代码注入的标记的名称EM> 即可。目前,下面的代码工作正常。
{% block body_block %}
{% if topics %}
{% for topic in topics %}
<div class="content-block" id= {{ topic.section_num }}>
<div class="row ">
<div class="col " align="center">
<h2>{% autoescape off %}{{ topic.section }}{% endautoescape %} </h2>
</div>
</div>
<div class="row ">
<div class="col-md-12 ">
{% if topic.div_element == "div_plot_donut" %}
<div class="embed-responsive embed-responsive-8by9">
{{div_plot_donut|safe}}
</div>
{% elif topic.div_element == "div_line" %}
<div class="embed-responsive embed-responsive-8by9">
{{div_line|safe}}
</div>
{% elif topic.div_element == "div_bar" %}
<div class="embed-responsive embed-responsive-8by9">
{{div_bar|safe}}
</div>
{%else%}
<p>Not found</p>
{% endif %}
</div>
</div>
</div>
{% endfor %}
{% else %}
<p> Nothing found </p>
{% endif %}
正如您所看到的,if else部分看起来很愚蠢,我将topic.div_element与单个字符串值进行比较,然后将该值基本上作为标记添加。
{% if topic.div_element|stringformat:"s" == "div_plot_donut" %}
<div class="embed-responsive embed-responsive-8by9">
{{div_plot_donut|safe}}
</div>
{% elif topic.div_element == "div_line" %}
<div class="embed-responsive embed-responsive-8by9">
{{div_line|safe}}
</div>
有没有办法做这样的事情,而不是有一个if-else结构:
<div class="col-md-12 ">
<div class="embed-responsive embed-responsive-8by9">
{{topic.div_element|safe}}
</div>
</div>