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:
我试图从djangos正常请求 - 响应结构之外的数据库渲染django模板。但由于django模板的编译方式,它似乎并不重要。我想做这样的事情:
>>> 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?
你怎么做到这一点?
2 个解决方案
#1
30
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):
这没有什么复杂的,它与请求/响应结构没有任何关系。您需要做的就是将模板字符串传递给django.template.Template构造函数(顺便说一句,我已经更改了模型的名称,以避免混淆):
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)))
#2
9
There is a reusable app which loads templates from the database:
有一个可重用的应用程序从数据库加载模板:
http://django-dbtemplates.readthedocs.org/en/latest/
http://django-dbtemplates.readthedocs.org/en/latest/
#1
30
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):
这没有什么复杂的,它与请求/响应结构没有任何关系。您需要做的就是将模板字符串传递给django.template.Template构造函数(顺便说一句,我已经更改了模型的名称,以避免混淆):
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)))
#2
9
There is a reusable app which loads templates from the database:
有一个可重用的应用程序从数据库加载模板:
http://django-dbtemplates.readthedocs.org/en/latest/
http://django-dbtemplates.readthedocs.org/en/latest/