Python 如何使用从一个基础模板继承的多个模板?蟒蛇,烧瓶
我的目录结构如下(来源): 我的Python 如何使用从一个基础模板继承的多个模板?蟒蛇,烧瓶,python,html,templates,flask,web-deployment,Python,Html,Templates,Flask,Web Deployment,我的目录结构如下(来源): 我的hamlet.py应用程序使用以下函数初始化2页: from flask import render_template from app import app @app.route('/') @app.route('/index') @app.route('/instance') def index(): return render_template('index.html') def instance(): return render_te
hamlet.py
应用程序使用以下函数初始化2页:
from flask import render_template
from app import app
@app.route('/')
@app.route('/index')
@app.route('/instance')
def index():
return render_template('index.html')
def instance():
return render_template('instance.html')
instance.html
和index.html
都是从具有不同块内容的base.html
继承的,base.html如下所示:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Post Editor Z</title>
</head>
<body>
<div class="container">
{% block content %}{% endblock %}
</div><!-- /.container -->
</body>
</html>
如何解决instance.html和index.html将显示模板中定义的两个不同页面的问题?
是因为我在
hamlet.py
中错误地初始化了我的页面吗?我找到了解决问题的方法,但我不知道为什么它会起作用
将@app.route('/instance')
移动到instance()
工作之前:
from flask import render_template
from app import app
@app.route('/')
@app.route('/index')
def index():
return render_template('index.html')
@app.route('/instance')
def instance():
return render_template('instance.html')
它之所以有效,是因为
@app.route
是一个函数的装饰器。像以前一样编写,每个url都指向索引函数。这样你就有了/instance
的/instance()
和其他的索引()
。如果@app.route('/')
没有装饰任何东西,下一个函数是@app.route('index')
。默认页面将指向索引()
?@app.route('/')
在本例中与@app.route('/index')
一起修饰索引。现在您的默认页面是index()
。
{% extends "base.html" %}
{% block content %}
<div class="row">
<div class="col-lg-12">
Hello World
</div>
</div>
{% endblock %}
{% extends "base.html" %}
{% block content %}
<div class="row">
<div class="col-lg-12">
Some instance.
</div>
</div>
{% endblock %}
{% extends "abase.html" %}
{% block content %}
<div class="row">
<div class="col-lg-12">
Hello World
</div>
</div>
{% endblock %}
from flask import render_template
from app import app
@app.route('/')
@app.route('/index')
def index():
return render_template('index.html')
@app.route('/instance')
def instance():
return render_template('instance.html')