如何处理模板继承中的变量

时间:2022-04-02 11:22:31

I just want to define id attribute of body tag in child template. First solution works perfectly:

我只想在子模板中定义body标签的id属性。第一个解决方案完美运

base.html:

[body{% block bodyid %}{% endblock %}]

child.html:

{% block bodyid %} id="myId"{% endblock %}

It's simple and cool! But I don't like to point id="myId" in every child template. I want just send value 'myId' to parent template, where it put to id="....". So, I invent this method:

这很简单,很酷!但我不喜欢在每个子模板中指出id =“myId”。我只想将值'myId'发送到父模板,它放在id =“....”。所以,我发明了这个方法:

base.html:

[body{% block bodyid %} id={{ bodyid }}{% endblock %}]

child.html:

{% block bodyid %}
    {% with 'myId' as bodyid %}
        {{ block.super }}
    {% endwith %}
{% endblock %}

But it's terrible and tedious to compare first solution. Is there any good method to do this?

但是比较第一个解决方案是非常糟糕和乏味的。有什么好方法可以做到这一点吗?

This problem is deeper, than managing bodyId. I think, I try to find and organize subtemplate system through standard django template's inheritance.

这个问题比管理bodyId更深入。我想,我尝试通过标准的django模板继承来查找和组织子模板系统。

2 个解决方案

#1


In the base template:

在基本模板中:

<body id="{% block bodyid %}{% endblock %}">

In the child template:

在子模板中:

{% block bodyid %}myId{% endblock %}

If I understand your question correctly, this should be sufficient to achieve what you want; only send the actualy ID (myId) to the base template.

如果我理解你的问题,这应该足以实现你想要的;仅将实际ID(myId)发送到基本模板。

#2


You, if you prefer, set this via your code - so that your id's are part of your context object, and therefor are not required to be entered in the child templates, just the views that call them.

如果您愿意,可以通过代码设置它 - 这样您的id就是上下文对象的一部分,因此不需要在子模板中输入,只需要调用它们的视图。

You can then tell your base template to get the id from the context object, or rather just use the template syntax for it:

然后,您可以告诉您的基本模板从上下文对象获取id,或者只是使用模板语法:

<body id="{{ body_id }}">

Personal preference here of course, and it depends on the structure of your templates and views, but its the way I'd do it.

当然,这里的个人偏好,取决于模板和视图的结构,但它取决于我的方式。

#1


In the base template:

在基本模板中:

<body id="{% block bodyid %}{% endblock %}">

In the child template:

在子模板中:

{% block bodyid %}myId{% endblock %}

If I understand your question correctly, this should be sufficient to achieve what you want; only send the actualy ID (myId) to the base template.

如果我理解你的问题,这应该足以实现你想要的;仅将实际ID(myId)发送到基本模板。

#2


You, if you prefer, set this via your code - so that your id's are part of your context object, and therefor are not required to be entered in the child templates, just the views that call them.

如果您愿意,可以通过代码设置它 - 这样您的id就是上下文对象的一部分,因此不需要在子模板中输入,只需要调用它们的视图。

You can then tell your base template to get the id from the context object, or rather just use the template syntax for it:

然后,您可以告诉您的基本模板从上下文对象获取id,或者只是使用模板语法:

<body id="{{ body_id }}">

Personal preference here of course, and it depends on the structure of your templates and views, but its the way I'd do it.

当然,这里的个人偏好,取决于模板和视图的结构,但它取决于我的方式。