【问题标题】:Load django template from the database从数据库加载 django 模板
【发布时间】:2011-01-28 14:24:07
【问题描述】:

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

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

你是怎么做到的?

【问题讨论】:

  • 我只是想知道您将如何更新您的模板?你将打破 MVC/T django 模型框架

标签: django django-models django-templates


【解决方案1】:

这没有什么复杂的,它与请求/响应结构没有任何关系。您需要做的就是将模板字符串传递给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)))

【讨论】:

  • AFAICT 您需要将参数 dict 包装在对 Context() 的调用中以使其工作,即:from django.template import Context; tpl.render(Context({'a' : 123, 'b' : 456}))
【解决方案2】:

有一个可重用的应用程序可以从数据库中加载模板:

http://django-dbtemplates.readthedocs.org/en/latest/

【讨论】:

  • 遗憾的是,它似乎被遗弃了。PyPI 的最后一个版本是 2012 年的。
  • @user1496984 - 但GitHub 已于 6 个月前更新。
猜你喜欢
  • 2010-09-26
  • 2014-05-10
  • 1970-01-01
  • 2013-10-12
  • 2019-10-27
  • 2013-07-26
  • 2016-09-08
  • 2013-05-09
  • 1970-01-01
相关资源
最近更新 更多