python - Flask 模板:链接 html 页面
问题描述
我是 Flask 的新手。我有 index1.html 作为我的主页。我添加了一个导航栏,其中包含指向其他 html 页面的链接。我该怎么做?
nav>
<button type="button" id="nav-toggle" onclick="$('nav ul').toggle()">☰MENU</button>
<ul>
<li class="active"><a href="index1.html" class="nav_tab" id="_a">Overview</a></li>
<li><a href="search.html" class="nav_tab" id="_b">Search</a></li>
</ul>
</nav>
html 页面位于模板文件夹中。“概览”链接应指向主页 (index1.html),而“搜索”应指向 search.html 页面。我怎样才能在烧瓶中实现这一点?我的 routes.py 看起来像这样:
from flask import render_template
from tomvar import app
@app.route('/')
@app.route('/index')
def index():
return render_template('index1.html')
解决方案
模板文件夹中的那些 HTML 页面必须在您的 routes.py 中的某个路由后面,因此您应该只在 HTML href 标记中定义路由,有点像这样。单击示例将带您进入/search
将为您search.html
打开的页面。
<li class="active"><a href="/search">Example</a></li>
第二种选择
或者还有另一种解决方案,您可以使用 url_for 生成应用程序中定义的路由的 url。
路线.py:
from flask import Flask, request, url_for, redirect, render_template
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/index2', methods=['GET', 'POST'])
def index_func():
if request.method == 'POST':
# do stuff when the form is submitted
# redirect to end the POST handling
# the redirect can be to the same route or somewhere else
return redirect(url_for('index'))
# show the form, it wasn't submitted
return render_template('index2.html')
模板/index.html:
<!doctype html>
<html>
<body>
<p><a href="{{ url_for('index_func') }}">Check out</a></p>
</body>
</html>
推荐阅读
- mysql - 按两列小数点后的特定数字选择
- java - 如何使用杰克逊有条件地(在其他属性上)反序列化属性?
- navigation - 如何在 Jssor 中自定义箭头导航
- mysql - SQL:过滤掉列值出现多次的行
- javascript - 从外部 url 获取特定内容 - PHP
- php - 在php中使用正则表达式查找化学式的所有实例
- php - 将存储在会话中的值传递到联系表单 7 中的输入字段
- azure-devops - azure devops 中的“摘要”选项卡上未显示代码覆盖率
- reactjs - “意外令牌”将尝试 react-datepicker
- javascript - 如何根据动态定义的变量解构对象