【问题标题】:Variables in Navigation pass to base and all template in Jinja 2Navigation 中的变量传递给 Jinja 2 中的 base 和所有模板
【发布时间】:2017-08-03 08:10:32
【问题描述】:

我有一个NavHandler 来传递导航页面的 json 数据。我想将导航包含到基础中,以便所有页面都可以看到导航。

我可以在nav.html 中看到 JSON 数据,但它没有显示在 base.htmlindex.html 中。

我可以知道如何将变量传递给所有模板吗?

我错过了什么?

此外,我还按照 Jinja2 示例代码测试了 @app.context_processor 和 nav.html,但给出了未定义的变量。

ma​​in.py

from flask import Flask
app = Flask(__name__)

@app.context_processor
def utility_processor():
    def format_price(amount, currency=u''):
        return u'{0:.2f}{1}'.format(amount, currency)
    return dict(format_price=format_price)

class NavHandler(weapp2.RequestHandler):
    def get(self):
        json_str = '''[{"name":"Nav A", "link":"link 1"},{"name":"Nav B", "link":"link 2"},{"name":"Nav C", "link":"link 3"}]'''
        json_data = json.load(json_str)
        template_vars = json_data

        template = JINJA_ENVIRONMENT.get.template('nav.html')
        self.response.write(template.render(template_vars, jason_data=json=data))

class BaseHandler(weapp2.RequestHandler):
    def get(self):

        template_vars = { 'title' : title}

        template = JINJA_ENVIRONMENT.get.template('nav.html')
        self.response.write(template.render(template_vars))

nav.html

{% block nav %}
    <ul>
    {% for d from json_data %}
        <li><a href="{{ d.link }}">{{ d.name }}</a>
    {% endfor %}
    </ul>
    <script> 
            console.log({{ format_price(0.33) }});
    </script>
{ endblock %} 

base.html

<!doctype html>
<html>
    <head>
        <meta charset="utf-8"/>
        <title>{% block title %} - My Site</title>
    </head>
    <body>
        <div>Navbar</div>
        {% include nav.html %}
        {% block content %}{% endblock %}

    </body>
</html>

index.html

{% extends 'base.html' %}

{% block content %}
<h3>{% block title %}Home{% endblock %}</h3>
<p>Hello, World!</p>
{% endblock %}

【问题讨论】:

    标签: python json templates variables jinja2


    【解决方案1】:

    您可以使用context processor 在模板中注入全局变量。

    要将新变量自动注入到模板的上下文中, Flask 中存在上下文处理器。上下文处理器在 模板被渲染并能够将新值注入 模板上下文。

    结帐this questionthis answer,他们可能会帮助你。

    编辑:用于新问题更新

    改变这一行:

    return dict(format_price=g.format_price)

    对于这个:

    return dict(format_price=format_price)

    【讨论】:

    • 所以我必须导入flask?
    • 我已经将flask安装到app lib中,然后我在这里按照Jinja示例:flask.pocoo.org/docs/0.10/templating/#context-processors当我在模板'nav.html'中尝试{{ format_price(0.33)}}时,它把我扔了以下错误: UndefinedError: 'format_price' 未定义。有什么想法吗?
    • @dnez 不看代码就没有想法,但为此我建议您提出另一个问题,重点关注上下文处理器的范围,否则更新此问题的正文。
    • @dnez 检查答案的编辑,看看 thar 是否适合你。
    • 删除了 g.仍然'UndefinedError:'format_price'未定义'
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-05
    • 2014-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多