【发布时间】:2017-08-03 08:10:32
【问题描述】:
我有一个NavHandler 来传递导航页面的 json 数据。我想将导航包含到基础中,以便所有页面都可以看到导航。
我可以在nav.html 中看到 JSON 数据,但它没有显示在 base.html 和 index.html 中。
我可以知道如何将变量传递给所有模板吗?
我错过了什么?
此外,我还按照 Jinja2 示例代码测试了 @app.context_processor 和 nav.html,但给出了未定义的变量。
main.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