django template - parse variable inside string variable

放肆的年华 提交于 2020-01-13 11:43:31

问题


I'm pulling a dynamic content(from a database) to a template. You can think of this as some simple CMS system. The content string contains a template variable. Like this one (simplified case):

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)

then in template:

{{content}}

output obviously:
the current city is: {{current_city}}
expected:
the current city is: London

My question - is there any way to render a variable name inside another variable? Using custom template tag/filter seems to be a good idea but I was trying to create one with no success... Any ideas how this can be solved?


回答1:


Having a custom tag can probably solve this issue, however it might get a little complicated because then there is a possibility of having a full template within a template since nothing restricts you from saving all of your templates in db (which might include other template tags). I think the easiest solution is to manually render the template string from the db, and then pass that as variable to the main template.

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:

If you do follow this road, this might not be very efficient since every time you will execute the view, the db template will have to be compiled. So then you might want to cache the compiled version of the db and then just pass the appropriate context to it. The following is very simple cache:

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)


来源:https://stackoverflow.com/questions/12811629/django-template-parse-variable-inside-string-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!