This is how to describe if else statements in Jinja 2 Template
Jinja 2 テンプレート内でのIf Else ステートメントの記述の仕方
========================================
Directory 構成
----
|--- test01.py
|---/templates
|
|--- sample01.html
|--- sample02.html
1. test01.py
from flask import Flask, render_template
app = Flask(__name__)
post_data =[
{
'Artist':'Justin Bieber',
'Birthday':'March 1, 1994',
'Title': 'Sorry',
'Year_Released':'2016'
},
{
'Artist':'Taylor Swift',
'Birthday':'December 13, 1989',
'Title': 'We Are Never Ever Getting Back Together',
'Year_Released':'2012'
}
]
@app.route('/')
@app.route('/home')
def home():
return render_template("sample01.html", posts=post_data)
@app.route('/about')
def about():
return render_template("sample02.html", title="About")
if __name__ == '__main__':
app.run(debug=True)
2. sample01.text
<html>
<head>
<meta charset="utf-8">
{% if title %}
<title>MossyMob Blog - {{ title }}</title> #titleが指定されていればtitleの値を表示
{% else %}
title>MossyMob Blog</title>
{% endif %}
</head>
</body>
{% for post in posts %}
<h1>{{ post.Artist }} </h1>
<p>Born in {{ post.Birthday }}</p>
<p> Title is {{post.Title}} released in {{ post.Year_Released }}
{% endfor %}
</body>
</html>
3.sample02.html
<html>
<head>
<meta charset="utf-8">
{% if title %}
<title> MossyMob - {{ title }}</title>
{% else %}
<title> MossyMob Blog</title>
{% endif %}
</head>
</body>
<p>Sample02 Page: About</p>
</body>
</html>
0 件のコメント:
コメントを投稿