Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何替换Django中占位符(变量)中的占位符?_Django_Django Templates - Fatal编程技术网

如何替换Django中占位符(变量)中的占位符?

如何替换Django中占位符(变量)中的占位符?,django,django-templates,Django,Django Templates,在Django模板中,我想添加来自模型字段的文本。此文本字段可以理解为文本模板本身。它可能看起来像: Dear {{user}}, thank your for... Regards, {{sender}} 此文本字段在普通Django模板中作为emailtemplate提供。上面的字段(user=Joe,sender=Alice)也可用 {% extends 'base.html' %} {% block content %} {{ emailtemplate }} {% e

在Django模板中,我想添加来自模型字段的文本。此文本字段可以理解为文本模板本身。它可能看起来像:

Dear {{user}},
thank your for...
Regards,
  {{sender}}
此文本字段在普通Django模板中作为
emailtemplate
提供。上面的字段(
user
=Joe,
sender
=Alice)也可用

{% extends 'base.html' %}
{% block content %}

{{ emailtemplate }}    

{% endblock %}
输出应如下所示

Dear Joe,
thank your for...
Regards,
  Alice

我不知道如何使用内置方法来实现这一点。我唯一的想法是在将
emailtemplate
交给模板引擎之前手动解析它,这样就在视图中了。但我敢肯定,我不是第一个遇到这个问题的人。

经过几次修改后,我想出了以下解决方案。仔细检查谁可以修改/更改模板字符串,因为这可能是一个很大的安全漏洞,如果由错误的人修改

views.py

class YourView(TemplateView):    
    template_name = 'page.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context["emailtemplate"] = "Dear {{user}}, {{sender}}"
        context["user"] = "Joe"
        context["sender"] = "Alice"
        return context
page.html

{% extends 'base.html' %}
{% load core_tags %}

{% block content %}

{% foobar emailtemplate %}

{% endblock %}
your_-app/templatetags/core_-tags.py
(不要忘记
\uuuu-init\uuuuuuuuuuuupy
文件,以确保目录被视为Python包
您的_-app
也必须在
已安装的_-APPS
中):

另见:


我将编写一个自定义模板标记,基本上使用当前上下文数据使用
jinja2.template.render
django.template.template.render
。但我想知道是否有其他人提出了更优雅的解决方案。我想知道这是否不是您想要的解决方案,或者您是否使用了其他方法来解决您描述的问题?非常感谢!!我将html标记存储在django模型中,以便控制其他用户如何编辑它们。这现在允许用户在标记中包含合并字段。我差点就要问我自己的问题了,很高兴找到了这一页。
from django import template
from django.template import Template

register = template.Library()


@register.simple_tag(takes_context=True)
def foobar(context, ts):
    t = Template(template_string=ts)
    return t.render(context)