LoginSignup
0
1

More than 3 years have passed since last update.

(自分用)Flask_2(リストとfor、extends、その他少し)

Last updated at Posted at 2020-06-17

項目

  1. py内で作ったリストをhtmlに渡す
  2. html内でpython形式のfor文
  3. extendsとかblock contentとかでhtmlの頭を省略
  4. 雑記

1.py内で作ったリストをhtmlに渡す

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

@app.route("/")
def hello_world():
    name = "Flask"
    players = ["勇者", "戦士", "魔法使い"]
    return render_template("index.html", name_value = name, players = players)
  • リスト自体は通常通り作成
  • htmlへの渡し方も他変数と同様

2.html内でpython形式のfor文

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    {% for player in players: %}
        <p>{{ player + "はモンスターを戦った" }}</p>
    {% endfor %}
</body>
</html>
  • for文の書き方自体は、前回のif文同様に{% ~~ %}で囲む
  • 最後に{% endfor %}を入れて締める

3.extendsとかblock contentとかでhtmlの頭を省略

py側でindex.htmlを参照していた場合

index.html
{% extends "layout.html" %}
{% block content %}
    <h1>aiueo</h1>
{% endblock %}
layout.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    {% block content %}
    {% endblock %}
</body>
</html>
  • テンプレート元として使いたいhtmlは、<body>の中で{% block content %}の直後に{% endblock %}を置く
  • テンプレートを使いたいhtmlは、{% extends "~~.html" %}で、参照する相手を選択する
  • その後<head><body>とかのタグを消して、代わりに入力したいものを{% block content %}{% endblock %}の中に入れる
  • index内で入力したものが{% block content %}というワープゲートを通って、layout{% block content %}の所へ転送されたイメージ

4.雑記

  • 似たような形式で表示されるものは、html側は1つに纏めちゃって、py側で下みたいに変数とかパスとか変えてやると楽そう
python
player = "プレイヤー"

@app.route("/walk")
def walk():
    message = player + "は荒野を歩いていた。"
    return render_template("action.html", player = player, message = message)

@app.route("/attack")
def attack():
    message = player + "はモンスターと戦った。"
    return render_template("action.html", player = player, message = message)
html
{% extends "layout.html" %}
{% block content %}
    <h1>{{ player }}のアクション</h1>
    <p>{{ message }}</p>
{% endblock %}
  • 慣れるまでこういうの思いつかなそう

5.終わりに

  • Flaskやる時間が全然無い、週末と来週に期待
0
1
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
0
1