Jinja2在扩展时重复内容
我在使用index.html继承自base.html的时候遇到问题,Jinja2把内容重复显示了。
我在用这个链接里的示例代码,但在浏览器里看到的内容完全重复。我不知道是不是因为Jinja的环境设置出错,或者是extends标签的问题,或者其他什么原因。
base.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="en">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
{% block head %}
<link rel="stylesheet" href="style.css" />
<title>{% block title %}{% endblock %} - My Webpage</title>
{% endblock %}
</head>
<body>
<div id="content">{% block content %}{% endblock %}</div>
<div id="footer">
{% block footer %}
© Copyright 2008 by <a href="http://domain.invalid/">you</a>.
{% endblock %}
</div>
</body>
index.html
{% extends "base.html" %}
{% block title %}Index{% endblock %}
{% block head %}
{{ super() }}
<style type="text/css">
.important { color: #336699; }
</style>
{% endblock %}
{% block content %}
<h1>Index</h1>
<p class="important">
Welcome on my awesome homepage.
</p>
{% endblock %}
我看到的内容是这样的(同样的HTML代码出现了两次):
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="en">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<link rel="stylesheet" href="style.css" />
<title>Index - My Webpage</title>
<style type="text/css">
.important { color: #336699; }
</style>
</head>
<body>
<div id="content">
<h1>Index</h1>
<p class="important">
Welcome on my awesome homepage.
</p>
</div>
<div id="footer">
© Copyright 2008 by <a href="http://domain.invalid/">you</a>.
</div>
</body>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="en">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<link rel="stylesheet" href="style.css" />
<title>Index - My Webpage</title>
<style type="text/css">
.important { color: #336699; }
</style>
</head>
<body>
<div id="content">
<h1>Index</h1>
<p class="important">
Welcome on my awesome homepage.
</p>
</div>
<div id="footer">
© Copyright 2008 by <a href="http://domain.invalid/">you</a>.
</div>
</body>
有什么想法吗?非常感谢。
更新!!
这是我的处理程序。我在用webapp2。
class LandingHandler(webapp2.RequestHandler):
def get(self):
template = settings.JINJA_ENVIRONMENT.get_template('index.html')
self.response.write(template.render(dict()))
更新 2!!
在我的settings.py里
JINJA_ENVIRONMENT = jinja2.Environment(
loader=jinja2.FileSystemLoader(os.path.join(os.path.dirname(__file__),'templates')),
extensions=['jinja2.ext.autoescape'],
autoescape=True)
1 个回答
3
关于Jinja和Bootstrap,有点奇怪的地方。它在给出警告之前,会考虑到HTML注释。所以如果你在那个文件里有任何注释,比如说一个被注释掉的{% block content %} ... {% endblock %}
部分,最好把它完全删掉,这样就能正常工作了。