from flask import Flask
app = Flask(__name__)
@app.route('/')
def index():
return '<html><body><h1>Hello World'</h1></body></html>'
if __name__ == '__main__':
app.run(debug = True)
วิธีลดความซับซ้อนโดยใช้ Jinja2 template engine เป็นตัวประสานงานกับ Flask ในการแสดงผล รับค่า โดยใช้ function render_template()
from flask import Flask
app = Flask(__name__)
@app.route('/')
def index():
return render_template(‘hello.html’)
if __name__ == '__main__':
app.run(debug = True)
โดยมีโครงสร้างบังคับต้องมี Directory templates อยุ่ที่ path เดียวกับ script เช่น
/Application folder
|-app.py
|/templates
|-hello.html
โดยการทำงานจะเหมือน PHP คือ สามารถส่ง variable ไปยัง html เพื่อสร้าง dynamic web page ขึ้นมาเช่นhello.html
<!doctype html>
<html>
<body>
<h1>Hello {{ name }}!</h1>
</body>
</html>
app.pyfrom flask import Flask, render_template
app = Flask(__name__)
@app.route('/hello/<user>')
def hello_name(user):
return render_template('hello.html', name = user)
if __name__ == '__main__':
app.run(debug = True)
Jinja2 teamplate engine ใช้เครื่องหมายในการประกาศตัวแปร หรือ การทำงานดังนี้
{%...%} สำหรับ ประกาศคำสั่ง
{{...}} สำหรับ ประกาศตัวแปร
{#...#} สำหรับ coment แต่ไม่แสดงที่ output
#...## สำหรับ comment แสดงที่ output
เช่น
app.py
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/result')
def result():
dict = {'phy':50,'che':60,'maths':70}
items = [{'name': 'Ice cream', 'price': 50},
{'name': 'Cookie', 'price': 35},
{'name': 'Chocolate', 'price': 40},
{'name': 'Milk', 'price': 32.5}]
return render_template('result.html', result = dict, items = items)
if __name__ == '__main__':
app.run(host='127.0.0.1', port=8080,debug=True)
result.html<!doctype html>
<html>
<body>
<table border = 1>
{% for key, value in result.items() %}
<tr>
<th> {{ key }} </th>
<td> {{ value }} </td>
</tr>
{% endfor %}
</table>
<hr>
<ul>
{% for item in items %}
<li>{{item.name}} Price: {{item.price}}</li>
{% endfor %}
</ul>
</body>
</html>
* result.iteritems() ใช้งานบน python3 ไม่ได้ ให้เปลี่ยนเป็น result.items()
จะแสดงผลได้แบบนี้
ไม่มีความคิดเห็น:
แสดงความคิดเห็น