LoginSignup
4
5

More than 3 years have passed since last update.

Flask 使い回しhtmlの書き方

Last updated at Posted at 2019-12-10

備忘録として。

templates/index.html
{% extends 'base.html' %}
{% block main %}
    <main>
        <p>メインコンテンツ</p>
        <p><a href="/another">別ページへ行く</a></p>
    </main>
{% endblock %}
templates/another.html
{% extends 'base.html' %}
{% block main %}
    <main>
        <p>アナザーコンテンツ</p>
        <p><a href="/">トップページへ戻る</a></p>
    </main>
{% endblock %}
templates/base.html
<html>
    <head>
        <title>Flask lesson</title>
    </head>
    <body>
    <header>
        <div><h1>HEADER</h1></div>
        <hr>
    </header>    
{% block main %}
{% endblock %}
    <footer>
        <hr>
        <div><h1>FOOTER</h1></div>
    </footer>
    </body>
</html>
run.py
from flask import Flask,render_template
app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/another')
def second():
    return render_template('another.html')

app.debug =  True
app.run()
  • extendsは拡張するという意味
  • {% extends ~~~.html %}で、拡張先のhtmlを指定する
  • {% block ~~~ %}{% endblock %}で埋め込みたいコードを囲う、拡張先には埋め込みたい場所に書く
  • 複数の{% block ~~~ %}{% endblock %}を書いて埋め込むこともできる

PHPのincludeの方が管理しやすいかもなあ。

4
5
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
4
5