gpt4 book ai didi

python - Django:如何重新分发包含可扩展 HTML 模板的项目/应用程序?

转载 作者:行者123 更新时间:2023-11-28 17:45:37 25 4
gpt4 key购买 nike

我正在通读 Django 教程 How to write reusable apps .我想弄清楚如何打包 HTML 基本模板,以便安装我的应用程序(通过 pip)的人可以扩展它们(例如使用 {% extends %}。)当我导入 python 模块时,我不必知道它在文件系统中的位置,但 Django 模板就是这种情况吗?

(旁注:我的项目由管道组成,可以更轻松地编写特定类型的应用程序。因此我有各种抽象基类 [模型、 View 、表单]、模板标签、URL 配置和 HTML用户可以继承的模板。它还包含对 Django Admin 的自定义。现在它是一个项目,但我正在尝试将其打包为应用程序,因为根据我正在阅读的内容,这似乎是打包 Django 代码的正确方法,但也许我应该换一种方式。)

最佳答案

使用这样的模板目录结构:

awesome_app_name/
templates/
awesome_app_name/
base.html
cool_template.html

这允许其他人扩展您的模板:

{% extends 'awesome_app_name/cool_template.html' %}

或者他们可以像这样用自己的模板替换它:

my_app_name/
templates/
my_app_name/
my_template.html
awesome_app_name/
cool_template.html <-- this overloads your template with their own

这使得共享包中的模板非常灵活。

编辑:

如果您使用项目的模板目录和 app_directories.Loader template loader 配置 Django,这将起作用。 .我相信这是大多数人使用的配置:

TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
)

TEMPLATE_DIRS = (
# Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
os.path.join(PROJECT_DIR, 'templates'),
)

然后模板加载按以下顺序完成:

  1. 从项目目录解析模板
  2. 从应用目录解析模板

这是一个遵循此结构的示例项目:https://github.com/brutasse/django-password-reset

关于python - Django:如何重新分发包含可扩展 HTML 模板的项目/应用程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18675716/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com