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

标签 django templates filter render templatetag

我正在将动态内容(从数据库中)提取到模板中。您可以将其视为一些简单的 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}}
预期的:
当前城市是:伦敦

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

最佳答案

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

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)

笔记:

如果您确实遵循这条道路,这可能不是很有效,因为每次执行 View 时,都必须编译 db 模板。那么你可能想要缓存数据库的编译版本,然后将适当的上下文传递给它。以下是非常简单的缓存:
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 模板 - 解析字符串变量中的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12811629/

相关文章:

python - Django 无法使用 "python manage.py syncdb"命令创建默认表

c++ - 在 C++ 中实现 'bounded genericity'

c++ - 非最后一个参数包编译错误

javascript - 使用 Angular - 不显示基于其他数组项目的 Ng-Repeat 数组项目

c# - NHibernate 多对一连接子类与过滤器

excel - 如何在 Excel 中对合并的单元格进行排序/过滤?

python - 如果我只想在我的条目下面有一个简单的评论框,我应该使用 Django 的评论框架还是自己编写?

python - Django 信号总是同步的吗?

python - Django CORS X-FirePHP 版本

c++ - 通过基类指针获取子类类型