【问题标题】:django中的动态模板标签
【发布时间】:2022-01-23 16:52:46
【问题描述】:

我在 Django 中构建一个 html 页面,其结构如下:

{% extends 'main/base_template.html' %}
{% load filters %}

{% block main_window %}
<main class="col-md-9 ms-sm-auto col-lg-10 px-md-4">
    <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
        <h1 class="h2">Stuff</h1>
    </div>
    <div class="row mb-3">
        <div class="col-12 col-md-6">
            {% include 'main/stuff/stuff_A.html' %}
        </div>
        <div class="col-12 col-md-6">
            {% include 'main/stuff/stuff_B.html' %}
        </div>
    </div>
    <div class="row mb-3">
        <div class="col-12 col-md-6">
            {% include 'main/stuff/stuff_C.html' %}
        </div>
        <div class="col-12 col-md-6">
            {% include 'main/stuff/stuff_D.html' %}
        </div>
    </div>
{% endblock %}

并且每个stuff_X html文件的结构都是一样的,例如:

<div class="row mb-3">
    <div class="table-responsive">
        <table class="table table-striped table-sm caption-top" style="width:40em">
            <caption>Data</caption>
            <thead>
            <tr>
                <th scope="col">Data1</th>
                <th scope="col">Data2</th>
                <th scope="col">Data3</th>
            </tr>
            </thead>
            <tbody>
            <tr>
                <td id="stuff_a_data1" style="width:5em">{{ stuff_a.data1 }}</td>
                <td id="stuff_a_data2" style="width:5em">{{ stuff_a.data2 }}</td>
                <td id="stuff_a_data3" style="width:5em">{{ stuff_a.data2 }}</td>
            </tr>
            </tbody>
        </table>
    </div>
</div>

所以真正改变的只有一些 id 和要从 django 上下文中检索的数据的名称。

是否有任何机制允许我为这种情况编写通用页面?因为目前我正在处理 4 个(几乎)相同的页面,当我需要修改某些内容时,会在每个页面中添加 sn-ps 代码。

提前致谢!

【问题讨论】:

标签: python django django-templates


【解决方案1】:

我认为您可以通过使用将{{ stuff_a.data1 }} 概括为{{ foo.data1}}

{% with stuff_a as foo, 'stuff_a' as foo_id_tag %} 
        {% include 'main/stuff/foo.html' %}
{% endwith %}

假设模板在形式上确实相同,或者足够相似,您可以使用{%if ... %} 引导它们。 (ID 将变为 id="{{foo_id_tag}}_data1" 等)

另一种不难的方法是在你的python代码中使用format_html来生成你他们通过上下文传递给模板的东西。或者在相关模型上使用属性。类似的东西

class Foo ( models.Model):
    ...

    @property
    def bar (self):
        bar = max( self.a*3 - self.b, 0 ) 
        return f"{bar:.4}" 

所以你可以在你的模板中引用{{foo.bar}},它本身甚至不能对 foo 的字段进行微不足道的算术。

编辑:我忘记了 with 功能自 Django 1.something 以来已被纳入 %include。所以,更优雅,

{% include 'main/stuff/foo.html' with foo = stuff_a, foo_id_tag = 'stuff_a' %}

【讨论】:

    【解决方案2】:

    不确定这是否是您需要的,但您应该能够使用 add 模板过滤器连接字符串:

    {% with 'main/stuff/stuff_'|add:your_variable|add:'.html' as filename %}
      {% include filename %}
    {% endwith %}
    

    显然,您需要从您的views.py 中传递your_variable

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-03-23
      • 1970-01-01
      • 2015-12-17
      • 2011-04-25
      • 2021-12-16
      • 1970-01-01
      • 2013-04-02
      相关资源
      最近更新 更多