首页 > 解决方案 > 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')

标签: pythonhtmlflask

解决方案


模板文件夹中的那些 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>

推荐阅读