【问题标题】:Django: how do I redistribute a project/app that contains extendable HTML templates?Django:如何重新分发包含可扩展 HTML 模板的项目/应用程序?
【发布时间】:2013-09-11 14:42:39
【问题描述】:

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

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

【问题讨论】:

    标签: python django templates django-templates pip


    【解决方案1】:

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

    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

    【讨论】:

    • 但是 'awesome_app_name/cool_template.html' 引用了当前项目模板目录中的一个模板,对吧?而如果该软件包是通过 pip 安装的,那么它将位于 site-packages 中的某个位置。您链接到的项目说用户必须“创建一个 password_reset/base.html 模板”,而我希望用户从我的 base.html 继承。
    • 两者。我更新了答案以包含有关模板加载顺序的信息。 'awesome_app_name' 模板命名空间将存在于安装在站点包下的包中。但是使用您的包的开发人员可以在他们的项目模板目录中包含相同的命名空间,这将“重载”它。因为 'awesome_app_name' 命名空间存在于你的包中,它可以用于调用 {% extend %} (不需要重载)。
    猜你喜欢
    • 2013-06-13
    • 2010-11-27
    • 1970-01-01
    • 1970-01-01
    • 2014-01-02
    • 2018-03-20
    • 2011-04-27
    • 2019-03-05
    • 2019-04-21
    相关资源
    最近更新 更多