Django 模板从 db 渲染并解释标签 [英] Django template render from db and interprets tags

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

问题描述

urls.py

url(r'^/mailing/(?P<pk>d+)/preview/$', PreView.as_view(), name="preview"),

models.py

class Message(models.Model):
    # ... other fields ...
    body = models.TextField(_("Body"), help_text=_("You can use Django <a target='_blank' href='https://docs.djangoproject.com/en/dev/ref/templates/builtins/'>template tags</a>"))

views.py

class PreView(TemplateView):
    template_name = "mailing/preview.html"

    def get_context_data(self, pk, **kwargs):
        try:
            return {"message": Message.objects.get(id=pk)}
        except Message.DoestNotExist:
            raise Http404

template/mailing/preview.html

<div id="body">{{ message.body|safe }}</div>

然而 django 模板标签不被解释,只呈现为一个字符串.我想用一个

however django templatetags are not interpreted, only rendered as a string. I would like to use a

{% now "Y-m-d" %}

消息正文中的标记.将来需要使用任何其他标签.

tag in message body. In future there will be need to use any other tag.

我已经管理了两种工作方法,它们都不能让我满意.

I have managed two working approaches, both of them are not satisfying me.

  • 使用正则表达式和替换,
  • 将整个模板源放入 db TextField(文件的 insted)中,并从中呈现一个页面(模板).

我也在考虑创建从 Message.body 中返回渲染模板的模板标签.但是我不太确定它是好是坏.

I am also thinking about creating templatetag which returns a rendered template out of Message.body. However I am not quite sure whether it will be good or wrong.

你有什么建议吗?

推荐答案

你必须使用 Django 模板系统

from django.template.loader import get_template_from_string
from django.template.context import Context

return {"message": message, "body": get_template_from_string(message.body).render(Context())}

替代(和更漂亮)的解决方案可以是自定义模板过滤器:

Alternative (and prettier) solution can be custom template filter:

from django import template
from django.template.defaultfilters import stringfilter

register = template.Library()

@register.filter
@stringfilter
def render(value):
    return get_template_from_string(value).render(Context())

并使用:

{{message.body|render}}

这篇关于Django 模板从 db 渲染并解释标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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