首页 > 解决方案 > 阻止评估模板标签但不评估变量

问题描述

我正在使用 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 %}"

有没有办法将模板引擎配置为呈现变量但忽略标签和过滤器?或者我最好的选择是清理用户输入并尝试去除它们可能包含的所有标签和过滤器?

标签: djangodjango-templates

解决方案


推荐阅读