从数据库加载 django 模板 [英] Load django template from the database

查看:32
本文介绍了从数据库加载 django 模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从 djangos 正常请求-响应结构之外的数据库呈现 django 模板.但由于 django 模板的编译方式,这似乎并不重要.我想做这样的事情:

<预><代码>>>>s = Template.objects.get(pk = 123).content>>>some_method_to_render(s, {'a' : 123, 'b' : 456})>>>...这里渲染的输出...

你是怎么做到的?

解决方案

这没有什么复杂的,它与请求/响应结构没有任何关系.您需要做的就是将模板字符串传递给 django.template.Template 构造函数(顺便说一句,我已经更改了模型的名称,以避免混淆):

from django.template import Context, Template从 myapp.models 导入 DbTemplates = DbTemplate.objects.get(pk=123).contenttpl = 模板tpl.render(上下文(dict(a=123, b=456)))

Im trying to render a django template from a database outside of djangos normal request-response structure. But it appears to be non-trivial due to the way django templates are compiled. I want to do something like this:

>>> s = Template.objects.get(pk = 123).content
>>> some_method_to_render(s, {'a' : 123, 'b' : 456})
>>> ... the rendered output here ...

How do you do this?

解决方案

There's nothing complicated about this, and it doesn't have anything to do with the request/response structure. All you need to do is pass the template string into the django.template.Template constructor (BTW, I've changed the name of your model, to avoid confusion):

from django.template import Context, Template
from myapp.models import DbTemplate

s = DbTemplate.objects.get(pk=123).content
tpl = Template(s)
tpl.render(Context(dict(a=123, b=456)))

这篇关于从数据库加载 django 模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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