从命令行渲染Django模板,无需设置 [英] Render Django template from command line, without settings

查看:29
本文介绍了从命令行渲染Django模板,无需设置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法可以在不调用任何设置的情况下从命令行渲染Django模板?我想在任何Django应用或项目之外执行此操作,以便能够将其用作命令行工具来呈现带有一些变量的模板.有没有已经做到这一点的工具?Jinja2也可以.

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.

推荐答案

您可以使用

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

请注意,此答案适用于Django 1.8 +

Note that this answer is for Django 1.8+

这篇关于从命令行渲染Django模板,无需设置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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