从命令行渲染Django模板,不需要设置



有没有办法从命令行渲染Django模板而不调用任何设置?我想在任何Django应用程序或项目之外这样做,能够使用它作为命令行工具来渲染一些变量的模板。已经有这样的工具了吗?Jinja2也可以。

如果您没有任何自定义设置可以使用settings.configure()

from django.conf import settings
settings.configure()
from django.template import Template, Context
Template('Hello, {{ name }}!').render(Context({'name': 'world'}))

要从磁盘加载模板,您必须做更多的工作。

import django
from django.conf import settings
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': ['/path/to/template'],
    }
]
settings.configure(TEMPLATES=TEMPLATES)
django.setup()
from django.template.loader import get_template
from django.template import Context
template = get_template('my_template.html')
template.render(Context({'name': 'world'})

注意这个答案是针对Django 1.8+

相关内容

最新更新