阻止评估模板标签,但不评估变量

时间:2020-10-02 20:09:43

标签: django django-templates

我正在使用Django的模板引擎来评估用户提供的模板字符串。我想允许用户使用变量映射功能,但不能使用标签或过滤器。

例如:

from django.template import Context, Template

user_template_string = "V1: {{ var1 }}.  V2: {{ var2|truncatechars:5 }}.  {% if var3 %} yes {% else %} no {% endif %}"
template = Template(user_template_string)

context = {'var1': 'One',
           'var2': '123456789',
           'var3': True}

output = template.render(context=Context(context))
# Desired output:
# "V1: One.  V2: 123456789.  {% if var3 %} yes {% else %} no {% endif %}"

是否有一种方法可以配置模板引擎以呈现变量但忽略标签和过滤器?还是我最好的选择是清理用户输入并尝试去除它们可能包括的所有标签和过滤器?

0 个答案:

没有答案
相关问题