Django:覆盖和扩展应用程序模板 [英] Django: Overriding AND extending an app template

查看:29
本文介绍了Django:覆盖和扩展应用程序模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果您想覆盖 django 中的应用程序附带的模板(在 app/templates/app/中),您可以在另一个目录中创建一个同名的模板,模板加载器在应用程序的模板目录之前检查该模板.如果您只想覆盖模板的某些块,您还必须复制整个模板并更改该块,这实际上不是很 DRY.

If you want to override a template coming with an app in django (in app/templates/app/) you create a template of the same name in another directory, which the template loader checks before the app's template dir. If you just want to override certain blocks of the template you also have to copy the whole template and change that block, which is actually not very DRY.

有没有人知道一种覆盖原始模板的方法,同时扩展它,以便您只需要覆盖要更改的特定块?(这样做的目的是更改模板的名称,因为在某些情况下,您可能必须更改视图才能使其与另一个模板一起使用)

Does anybody know a way to override the orginial template, while at the same moment extending it, so that you just have to override the specific block you want to change? (the thing is doing this without changing the template's name, because in some cases you might have to change the view to make it work with another template)

正如 Adam Taylor 在 Django 1.9 的评论中指出的那样 这是可能的,无需任何黑客攻击.

As Adam Taylor pointed out in the comments from Django 1.9 on this is possible without any hacks.

推荐答案

我认为答案来自 这个相关问题 是相关的;目前,最好的解决方案似乎是使用 django-apptemplates 包中的自定义模板加载器PyPI,所以你可以使用 pip 来安装它(例如 pip installdjango-apptemplates).

I think the answer from this related question is pertinent; currently, the best solution seems to be to use a custom template loader from the django-apptemplates package on PyPI, so you can just use pip to install it (e.g. pip install django-apptemplates).

模板加载器允许您在特定应用程序中扩展模板;例如,要扩展管理界面的索引页,您将添加

The template loader allows you to extend a template in a specific app; for example, to extend the index page of the admin inteface, you would add

'apptemplates.Loader',

settings.py 中的 TEMPLATE_LOADERS 列表,并使用

to your TEMPLATE_LOADERS list in settings.py, and use

{% extends "admin:admin/index.html" %}

在您的模板中.

这篇关于Django:覆盖和扩展应用程序模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆