-->

Django的模板 - 解析变量中的字符串变量(django template - parse va

2019-09-23 20:41发布

我拉着动态内容(从数据库)为模板。 你可以认为这是一些简单的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}}
预期:
目前的城市是:伦敦

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

Answer 1:

有一个自定义标签或许可以解决这个问题,但它可能会有点复杂,因为再有就是具有模板内的完整的模板,因为没有从节约您的所有模板数据库(其中可能包括其他的模板标签限制您的可能性)。 我认为,最简单的方法是手动呈现来自数据库的模板字符串,然后传递可变的主模板。

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)

注意:

如果你沿着这条路,这可能不是非常有效的,因为每一次你将执行视图,数据库模板将不得不进行编译。 所以,那么你可能想缓存分贝的编译版本,然后只需通过适当的上下文它。 以下是非常简单的缓存:

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)


文章来源: django template - parse variable inside string variable