如何在Django项目中构造模板库? [英] How to structure template libraries in a Django project?

查看:36
本文介绍了如何在Django项目中构造模板库?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正处于开发过程的早期阶段,正在尝试找出构造网站模板库的最佳实践.

I'm in the early innings of the development process and am trying to figure out best practices for structuring the template libraries for a website.

我计划有一个基本"模板来扩展整个站点.我看到了一些示例,在这些示例中,在项目级别创建了一个模板目录来容纳此文件,而另一些示例中,在其中一个应用程序文件夹中创建了基本"文件,然后根据需要将其扩展到其他应用程序.有正确的方法吗?

I plan to have a "base" template to extend across the site. I have seen some examples where a template directory is created at the project level to house this file, and others where a "base" file is created in one of the app folders and then extended to other apps as needed. Is there a correct way this should be done?

在此非常基础的问题上,我先谢谢您的幽默.第一次尝试让我站稳脚跟.

Thank you in advance for humoring me on this extremely basic question. Trying to get my feet under me for the first time.

推荐答案

对于站点项目,我也倾向于将项目模块本身(由 startproject 创建)用作应用程序.

For site projects I tend to make the project module itself (as created by startproject) an app too.

这样,基本模板,基本模型(例如自定义用户模型!),助手实用程序功能等就可以在其中生活,而根本不必去烦恼文件系统模板加载器-默认应用程序基于模板的加载程序工作正常.

That way base templates, base models (such as a custom user model!), helper utility functions, etc. live in there, and one doesn't have to futz around with the filesystem template loaders at all - the default app-based template loader works fine.

也就是说,如果我的项目是 grocerystore ,并且它有两个应用程序,即 drinks foods (愚蠢的示例,但是我),结构大概是

That is, if my project is, say, grocerystore and it has two apps, drinks and foods (silly example but bear with me), the structure would be approximately

manage.py
grocerystore/
    __init__.py
    settings/
        __init__.py
    models/
        __init__.py
        user.py
    views/
        __init__.py
    templates/
        base.html
foods/
    __init__.py
    apps.py
    models/
        __init__.py
        food.py
    views/
        __init__.py
        food/
            __init__.py
            food_list_view.py
        __init__.py
    templates/
        foods/
            food_list.html
drinks/
    __init__.py
    apps.py
    models/
        __init__.py
        drink.py
    # ... etc ...

INSTALLED_APPS 将包含(以及Django默认值)(杂货店",食品",饮料").

and INSTALLED_APPS would contain (along Django defaults) ('grocerystore', 'foods', 'drinks').

然后,您可以在应用中简单地 {%扩展"base.html"%} .

You can then simply {% extends "base.html" %} in your apps.

(请注意,顺便说一句,为了能够将 models.py 拆分为一个包,您必须确保 models/__ init __.py 导入包含每个模块的模块模型,因此它们是由Django注册的!)

(Note, btw, that to be able to split models.py into a package, you have to make sure models/__init__.py imports the modules holding each model, so they're registered by Django!)

这篇关于如何在Django项目中构造模板库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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