django 模板 - 解析字符串变量内的变量

2024-01-17

我正在将动态内容(从数据库)拉到模板中。您可以将其视为一些简单的 CMS 系统。内容字符串包含模板变量。就像这个(简化的情况):

vars['current_city'] = "London"
vars['content'] = 'the current city is: {{current_city}}'  #this string comes from db
return render_template(request, 'about_me.html',vars)

然后在模板中:

{{content}}

输出明显:
当前城市是:{{current_city}}
预期的:
当前城市是: 伦敦

我的问题 - 有没有办法在另一个变量中呈现变量名称?使用自定义模板标签/过滤器似乎是一个好主意,但我试图创建一个但没有成功......有什么想法可以解决这个问题吗?


拥有自定义标签可能可以解决这个问题,但是它可能会变得有点复杂,因为模板中可能有完整的模板,因为没有什么限制您将所有模板保存在数据库中(可能包括其他模板标签) )。我认为最简单的解决方案是从数据库手动渲染模板字符串,然后将其作为变量传递给主模板。

from django.template import Template, Context
...
context = {
    'current_city': 'London'
}
db_template = Template('the current city is: {{current_city}}') # get from db
context['content'] = db_template.render(Context(context))
return render_template(request, 'about_me.html', context)

Note:

如果您确实遵循这条路,这可能不是很有效,因为每次执行视图时,都必须编译数据库模板。因此,您可能希望缓存数据库的编译版本,然后将适当的上下文传递给它。下面是非常简单的缓存:

simple_cache = {}

def fooview(request):
    context = {
        'current_city': 'London'
    }
    db_template_string = 'the current city is: {{current_city}}'
    if simple_cache.has_key(db_template_string):
        db_template = simple_cache.get(db_template_string)
    else:
        simple_cache[db_template_string] = Template(db_template_string)
    context['content'] = db_template.render(Context(context))
    return render_template(request, 'about_me.html', context)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

django 模板 - 解析字符串变量内的变量 的相关文章

随机推荐