LoginSignup
1
2

More than 3 years have passed since last update.

jinja2を使ってみた

Posted at

前回:Flaskを使ってwebアプリケーション開発の続きです。

ルーティングを追加

前回作成したapp.pyに新たなルーティングを追記していきます。

app.py
from flask import Flask, render_template
app = Flask(__name__)

# 略

@app.route("/hello/<whom>")
def hello(whom):
  return render_template("hello.html", whom=whom)

<whom>は変数となっていて、たとえば/hello/taroでアクセスした場合、whomにはtaroが入ってきます。

return render_template("hello.html", name=whom)では、ルーティングから受けっとったtaroを変数nameに代入することで、それをhello.htmlないで使用することができます。

テンプレートファイル作成

Flaskは、テンプレートをtemplatesフォルダから検索するため、ディレクトリtempletesを作成する必要があります。

$ midir templates

templetesの中にhello.htmlを作成します。

hello.html
<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="UTF-8">
  <title>Hello</title>
</head>
<body>
  <h1>Using Jinja2 Template engine</h1>
  <h2>Hello {{name}}</h2>
</body>
</html>

参考

VS CodeとFlaskによるWebアプリ開発「最初の一歩」

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2