Render Django template from command line, without settings

白昼怎懂夜的黑 提交于 2021-02-07 08:56:05

问题


Is there a way to render a Django template from command line without invoking any settings? I want to do this outside any Django apps or project, to be able to use it as a command line tool to render a template with some variables. Is there a tool that does this already? Jinja2 would be fine too.


回答1:


You can use settings.configure() if you don't have any custom settings to configure.

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

To load templates from disk, you have to do slightly more work.

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'})

Note that this answer is for Django 1.8+



来源:https://stackoverflow.com/questions/32442893/render-django-template-from-command-line-without-settings

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!