はじめに
この実験では、Flask でテンプレートを作成して使用する方法を学びます。テンプレートは Web アプリケーションの重要な部分です。これにより、読み込まれるたびに異なるデータを表示できる動的な HTML ページを生成できます。私たちは、Flask に同梱されている Jinja2 テンプレートエンジンを使用します。
注: コードファイルは自分で作成し、環境で実行する必要があります。Web 5000 で Flask サービスの状態をプレビューできます。
This tutorial is from open-source community. Access the source code
💡 このチュートリアルは英語版からAIによって翻訳されています。原文を確認するには、 ここをクリックしてください
この実験では、Flask でテンプレートを作成して使用する方法を学びます。テンプレートは Web アプリケーションの重要な部分です。これにより、読み込まれるたびに異なるデータを表示できる動的な HTML ページを生成できます。私たちは、Flask に同梱されている Jinja2 テンプレートエンジンを使用します。
注: コードファイルは自分で作成し、環境で実行する必要があります。Web 5000 で Flask サービスの状態をプレビューできます。
最初のステップは、すべてのページで使用する基本レイアウトを作成することです。この基本レイアウトには、ナビゲーションバーやページタイトルなど、アプリケーションの共通要素が含まれます。
<!-- flaskr/templates/base.html -->
<!doctype html>
<title>{% block title %}{% endblock %} - Flaskr</title>
<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}" />
<nav>
<h1>Flaskr</h1>
<ul>
{% if g.user %}
<li><span>{{ g.user['username'] }}</span></li>
<li><a href="{{ url_for('auth.logout') }}">Log Out</a> {% else %}</li>
<li><a href="{{ url_for('auth.register') }}">Register</a></li>
<li>
<a href="{{ url_for('auth.login') }}">Log In</a>
{% endif %}
</li>
</ul>
</nav>
<section class="content">
<header>{% block header %}{% endblock %}</header>
{% for message in get_flashed_messages() %}
<div class="flash">{{ message }}</div>
{% endfor %} {% block content %}{% endblock %}
</section>
次に、登録ページ用のテンプレートを作成します。このテンプレートは、基本レイアウトを拡張し、このページの特定のコンテンツを埋めます。
<!-- flaskr/templates/auth/register.html -->
{% extends 'base.html' %} {% block header %}
<h1>{% block title %}Register{% endblock %}</h1>
{% endblock %} {% block content %}
<form method="post">
<label for="username">Username</label>
<input name="username" id="username" required />
<label for="password">Password</label>
<input type="password" name="password" id="password" required />
<input type="submit" value="Register" />
</form>
{% endblock %}
同様に、ログインページ用のテンプレートを作成します。このテンプレートも基本レイアウトを拡張し、このページの特定のコンテンツを埋めます。
<!-- flaskr/templates/auth/login.html -->
{% extends 'base.html' %} {% block header %}
<h1>{% block title %}Log In{% endblock %}</h1>
{% endblock %} {% block content %}
<form method="post">
<label for="username">Username</label>
<input name="username" id="username" required />
<label for="password">Password</label>
<input type="password" name="password" id="password" required />
<input type="submit" value="Log In" />
</form>
{% endblock %}
この実験では、Flask でテンプレートを作成して使用する方法を学びました。アプリケーションの共通要素を含む基本レイアウトを作成し、その後、この基本レイアウトを拡張して特定のコンテンツを埋める登録ページとログインページ用の特定のテンプレートを作成しました。これにより、コードを DRY(繰り返さない)に保つことができ、保守性が向上し、エラーの発生率が低下します。