开发者

Django: TEMPLATE_DIRS vs INSTALLED_APPS

I am currently just add app to INSTALLED_APPS to be able to use templates from that app, but there is also TEMPLATE_DIRS setting. W开发者_Python百科hen have I to prefer TEMPLATE_DIRS over INSTALLED_APPS?


You can use templates in TEMPLATE_DIRS to either override templates coming from apps (by giving them the same name) or for templates that are relevant for more than one app (base.html comes to mind).

This works because of the order in which template loaders are set in TEMPLATE_LOADERS (filesystem before app_directories).

It's a good idea to organize your templates in the following way to avoid name collisions:

<project>/
    <app1>/templates/<app1>/
        foo.html
        bar.html
    <app2>/templates/<app2>/
        foo.html
    templates/
        <app1>/
            foo.html
        base.html
        xyzzy.html


You also need to define this TEMPLATE_DIRS in order to override external modules templates.

If your template folder located as hop recommended in previous answer, you can define the TEMPLATE_DIRS in this manner, to have it more portable:

import os

cwd = os.path.dirname(os.path.abspath(__file__))
PROJECT_ROOT = cwd[:-9]

# other code comes here ...

TEMPLATE_DIRS = (
    os.path.join(PROJECT_ROOT, "templates"),
)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜