python - 导航中的变量传递到 Jinja 2 中的基础和所有模板

标签 python json templates variables jinja2

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

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

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

我错过了什么?

此外,我还按照 Jinja2 示例代码来测试 @app.context_processor 和 nav.html,但给出了 undefined variable 。

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 %}

最佳答案

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

To inject new variables automatically into the context of a template, context processors exist in Flask. Context processors run before the template is rendered and have the ability to inject new values into the template context.

结账 this questionthis answer ,他们可能可以帮助您。

编辑:新问题更新

更改此行:

返回字典(format_price=g.format_price)

对于这个:

返回字典(format_price=format_price)

关于python - 导航中的变量传递到 Jinja 2 中的基础和所有模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45478433/

相关文章:

iphone - iPhone 的 JSON 库

json - 澳大利亚房地产 API(用于 google maps mashup)

c++ - 模板赋值运算符不会替换默认的赋值运算符

c++ - 使用带有 vector 和 vector 函数的模板

python - 基于密度的散点图中的颜色点

python - 在 Mac OS X 上的 IDE 中设置 Python 3 的路径

python - Pandas:使用合并单元格读取 Excel

Python MySQL参数查询动态表名

javascript - 仅当数据来自循环 GET 请求时,JSON stringify 才会失败

c# - 文本框 Silverlight 的样式