html - 避免在 django 模板 HTML 表中出现重复的 "if conditions"

标签 html django django-templates html-table

根据访问网页的用户,生成的 HTML 表格可能会显示额外的列。我当前的实现检查模板文件中每一行的标志,其中 show_secret_column 是由 View 设置的标志:

<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 表中出现重复的 "if conditions",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38757122/

相关文章:

html - 使用 Flexbox 构建网格 - 仅在右侧第二行的元素

html - doctype html 中薄图像的框模型问题?

django 使用 login_required 装饰器测试 DRY View

django - TypeError 对象不可迭代

jquery - 让div动态填充剩余空间

javascript - 悬停时在图像上显示链接

django - 如何创建基于 Django 中的单个条件过滤多个字段的查询集?

python - 为 ModelChoiceField 指定 CSS 类不起作用

python - 基于 Django 类的通用 View : cannot import name TemplateView

ModelFormset 的 Django 删除按钮操作