问题
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