根据访问网页的用户,生成的HTML表可能会显示额外的列。我当前的实现检查模板文件中每一行的标志,其中show_secret_column
是由视图设置的标志:
<div class="table-responsive">
<table class="table">
<thead>
<tr>
<th class="col-md-4">Column 1 Header</th>
<th class="col-md-2">Column 2 Header</th>
<th class="col-md-2">Column 3 Header</th>
{% if show_secret_column %}
<th class="col-md-2">Secret Column Header</th>
{% endif %}
</tr>
</thead>
<tbody>
{% for row in row %}
<tr>
<td>{{ row.a }}</td>
<td>{{ row.b }}</td>
<td>{{ row.c }}</td>
{% if show_secret_column %}
<td>{{ row.secret }}</td>
{% endif %}
</tr>
{% endfor %}
</tbody>
</table>
</div>
这是一个坏方法吗?是否有其他方法建议只在模板中执行此检查一次并生成额外的列?
最佳答案
如果您真的想对这么大的行数进行微观优化(我强烈建议您不要),您可以复制如下模板:
{% if show_secret_column %}
<thead>
<tr>
<th class="col-md-4">Column 1 Header</th>
<th class="col-md-2">Column 2 Header</th>
<th class="col-md-2">Column 3 Header</th>
<th class="col-md-2">Secret Column Header</th>
</tr>
</thead>
<tbody>
{% for row in row %}
<tr>
<td>{{ row.a }}</td>
<td>{{ row.b }}</td>
<td>{{ row.c }}</td>
<td>{{ row.secret }}</td>
</tr>
{% endfor %}
</tbody>
{% else %}
<thead>
<tr>
<th class="col-md-4">Column 1 Header</th>
<th class="col-md-2">Column 2 Header</th>
<th class="col-md-2">Column 3 Header</th>
</tr>
</thead>
<tbody>
{% for row in row %}
<tr>
<td>{{ row.a }}</td>
<td>{{ row.b }}</td>
<td>{{ row.c }}</td>
</tr>
{% endfor %}
</tbody>
{% endif %}
我只想重复一下,如果我在代码中看到这一点,我会很震惊。它现在非常脆弱(您必须小心复制对这两个部分所做的所有更改)。它也只是有很多臃肿和一个眼中钉。
您的主要目标应该是首先不要有一个包含40k行的表。也就是说,这会满足你的要求。
关于html - 避免在Django模板HTML表中重复“如果条件”,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38757122/