gpt4 book ai didi

python - Django 中命名空间模板的优雅方式

转载 作者:行者123 更新时间:2023-12-04 16:56:07 25 4
gpt4 key购买 nike

Django 教程建议这样组织模板:

Within the templates directory you have just created, create another directory called polls, and within that create a file called index.html. In other words, your template should be at polls/templates/polls/index.html. Because of how the app_directories template loader works as described above, you can refer to this template within Django simply as polls/index.html.



教程还说明了如果我将 index.html 放在 polls/templates 中会发生什么:

Now we might be able to get away with putting our templates directly in polls/templates (rather than creating another polls subdirectory), but it would actually be a bad idea. Django will choose the first template it finds whose name matches, and if you had a template with the same name in a different application, Django would be unable to distinguish between them. We need to be able to point Django at the right one, and the easiest way to ensure this is by namespacing them. That is, by putting those templates inside another directory named for the application itself.



我的假设是,只要我在创建一个独立的应用程序,它的模板也与其他应用程序隔离,没有任何子文件夹魔法。

有没有另一种命名空间的方法,所以我可以将模板称为 index.html 而不创建重复的文件夹?

最佳答案

Django 项目中组织模板的方式非常灵活。因此,只要您在 View 中指定正确的模板名称,就可以根据需要订购模板文件。例如,您可以对投票列表使用基于类的 View ,指定 template_name随心所欲:

# polls/views.py
from django.views.generic import ListView
from .models import Poll

class PollList(ListView):
model = Poll
template_name = 'any/path/you/choose/any_name.html'

话虽如此,最好创建一致的模板结构以保持代码的可维护性。我建议至少将您的页面级模板(用于返回整个 html 页面的内容)组织在具有相关应用程序名称的文件夹中,以及您包含的任何内容(包含在 {% include %} 标签中的片段) includes子文件夹,像这样:
templates
- base.html
polls
- poll_list.html
includes
- poll_votes.html

编辑:

如果你仍然需要命名空间,你可以使用 URL namespaces .

关于python - Django 中命名空间模板的优雅方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27144773/

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