Django template render from db and interprets tags

放肆的年华 提交于 2020-01-01 07:11:27

问题


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>

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.

  • Use regexps and substitutions,
  • Put whole template source in db TextField (insted of file), and renders a page(template) from it.

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.

Do you have any suggestions?


回答1:


You must use Django template system

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

EDIT:

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())

and use:

{{message.body|render}}


来源:https://stackoverflow.com/questions/7661560/django-template-render-from-db-and-interprets-tags

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!