Django - 定义模板包含/扩展在一处,就像在 urls.py 中定义 url 路径一样?
我真的很喜欢从 PHP 到 Python/Django 的过渡以及扩展模板的能力。然而,我仍然发现我仍然在定义模板和扩展其他模板等方面做相当多的重复工作。只是想知道是否有人知道有什么方法可以将所有这些抽象到一个文件中,该文件告诉其他模板模板应该扩展/包含?
I'm really enjoying the transition from PHP to Python/Django and the ability to extend templates. However, I'm still finding that I'm still doing a fair bit of repetitive work in defining templates and extending other templates, etc. Just wondering if anyone knows of any way to abstract all this out into one file which tells which templates other templates should extend/include?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
简单的答案是,不使用默认功能。将
{% base %}
标记等抽象到另一个文件将使模板更难以阅读。消除“额外工作”的一种方法是让你的编辑为你做这件事。就我而言,我将所有模板定义为
.dhtml
文件,并在每次打开空.dhtml
文件时让 VIM 将模板粘贴到该文件中。大多数以编程为中心的编辑器都内置了此功能,以防止您必须手动复制/粘贴或重新输入基本结构。另一件需要考虑的事情是,您可能以不太理想的方式构建模板本身。例如,如果您有不同的基本模板,您可以用 CSS 替换不同的基本模板吗? CSS 可以以程序员有时会忽略的方式更改模板。要获得一个很好的示例,请查看 CSS Zen Garden。您看到的变化是惊人的,而且它们根本没有改变基本的 HTML。
对于这样的更改,您可以简单地将其放在
templates/base.html
中:并且为了包含覆盖的 CSS,您可以将其放置在模板中:
The simple answer is, not with the default functionality. Abstracting things like the
{% base %}
tag to another file would make the templates much harder to read.One way to remove the "extra work" is to make your editor do it for you. In my case, I define all of my templates as
.dhtml
files and have VIM paste in a template into the file whenever I open an empty.dhtml
file. Most programming-centric editors have this functionality built in to prevent you from having to manually copy/paste or retype your basic structures.Another thing to consider is that you may be building the templates themselves in a less-than-optimal way. For example, if you have different base templates, could you replace the different base templates with CSS? CSS can change templates in ways that programmers can sometimes overlook. For a good example, check out the CSS Zen Garden. The changes you see are amazing, and they do not change the base HTML at all.
For a change like this, you could simply have this in
templates/base.html
:And in order to include an over-riding CSS, you place this in your templates: