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

查看:116
本文介绍了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 ad 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的评论中指出的那样, / a>这可能没有任何黑客。

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

推荐答案

我认为从这个相关的问题是相关的;目前,最好的解决方案似乎是使用 django-apptemplates包中的自定义模板加载程序PyPI ,因此您可以使用 pip 进行安装(例如 pip install django-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',

设置 TEMPLATE_LOADERS 列表.py ,并使用

to your TEMPLATE_LOADERS list in settings.py, and use

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

在您的模板中。

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

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