【问题标题】:django template - parse variable inside string variabledjango模板 - 在字符串变量中解析变量
【发布时间】:2012-09-30 11:15:16
【问题描述】:

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

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

【问题讨论】:

    标签: django templates filter render templatetag


    【解决方案1】:

    拥有一个自定义标签可能可以解决这个问题,但是它可能会变得有点复杂,因为这样就有可能在一个模板中拥有一个完整的模板,因为没有什么限制你将所有模板保存在 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)
    

    注意:

    如果你真的走这条路,这可能不是很有效,因为每次执行视图时,都必须编译 db 模板。因此,您可能想要缓存 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)
    

    【讨论】:

    • 谢谢。是的,从一个观点来看,这不是什么大问题,因为我们拥有所有可用的变量。如果无法在视图内进行解析怎么办?如果我们可以在视图之外自动为当前页面提取此内容,那将是理想的,这样我们就不必记住它,例如在模板上下文处理器中。然后我们最终得到一个字符串中的变量名,但是在这种情况下如何访问模板变量来渲染字符串呢?
    猜你喜欢
    • 1970-01-01
    • 2011-05-15
    • 2023-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多