Flask-Template-Parameter

テンプレート
テンプレートは、Web開発に必要なモジュールです。Webページをレンダリングするとき、プレーンテキスト文字列をレンダリングするだけでなく、リッチテキストタグを使用してページをレンダリングする必要があるからです。現時点では、テンプレートを使用する必要があります。Flaskでは、サポートテンプレートはJinja2であり、Jinja2の作者はFlaskの作者でもあります。このテンプレートは非常に強力で非常に効率的です。以下はJinja2の簡単な紹介です!
FlaskレンダリングJinjaテンプレートテンプレート
をレンダリングするには、render_templateメソッドを使用できます。

/ profile /にアクセスすると、profile()関数は、現在のディレクトリのテンプレートフォルダーでindex.htmlテンプレートファイルを探します。テンプレートファイルのアドレスを変更する場合は、キーワードパラメータtemplate_folderをFlaskに渡し、アプリの作成時に特定のパスを指定する必要があります

index.htmlプロファイル/ user.htmlを作成します

# @ Time : 2020/4/9 22:45
# @ Author : Ellen

from flask import Flask,render_template

# app = Flask(__name__)
app = Flask(__name__,template_folder=r"./demo")

@app.route("/")
def index():
    return render_template("index.html")
    
    以上例子将会在C盘的templates文件夹中寻找模板文件。还有最后一点是,如果模板文件中有参数需要传递,应该怎么传呢

@app.route("/profile/")
def profile():
    # 默认会从tempalates目录下面找模板文件
    return render_template("profile/user.html")


if __name__ == '__main__':
    app.run(debug=True, port=8000)

上記の例では、パラメーターを渡す2つの方法を紹介していますが、render_templateはキーワードパラメーターを渡す必要があるため、最初の方法が自然です。ただし、テンプレートに渡すパラメータが多すぎる場合は、すべてのパラメータを関数に入れるのは明らかに良い選択ではないため、辞書を使用して2つの*記号をラップして追加し、キーワードパラメータに変換します。 。

# @ Time : 2020/4/9 22:45
# @ Author : Ellen

from flask import Flask,render_template

app = Flask(__name__)
# app = Flask(__name__,template_folder=r"./demo")

@app.route("/")
def index():
    # return render_template("index.html",username="张胜利的幸福生活",age=18)
    context = {
        "username": "张胜利的幸福生活",
        "age": "18",
        "books": {
            "python": 33,
            "java": 23,
            "PHP": 28
    },
        "book":["python","PHP","Java"]

    }
    # username="张胜利的幸福生活"
    return render_template("index.html",**context)

@app.route("/profile/")
def profile():
    # 默认会从tempalates目录下面找模板文件
    return render_template("profile/user.html")


if __name__ == '__main__':
    app.run(debug=True, port=8000)

作成:index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <input type="text" class="s_ipt" name="wd" id="kw" maxlength="100" autocomplete="off">
    <h1>{{username}}</h1>
    <h2>{{age}}</h2>
   {# <h2>{{context.username}}</h2> #}
    <!--字典嵌套取值-->
    <h4>{{books.python}}</h4>
    <h4>{{books['python']}}</h4>
    <!--列表取值 可以用下标取值-->
    <h4>{{book.2}}</h4>
    <h4>{{book[1]}}</h4>
</body>
</html>
公開された118元の記事 ウォンの賞賛0 ビュー2665

おすすめ

転載: blog.csdn.net/weixin_45905671/article/details/105422365