2018年9月30日 星期日

Flask Jinja2

Jinja2是Flask默認支持的模版引擎,主要作用是渲染模板。

在layout.html中,用{% block body %}和{% endblock %}來綁訂其他頁面內容。所以在這個網頁中,我們可以制定網頁中共用的模板。

<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <title>MyFlaskApp</title>
</head><body>{% block body %} {% endblock %}
</body></html>

另外我們在home.html指定引用layout.html,並撰寫{% block body %}和{% endblock %}之間的網頁內容。

{% extends 'layout.html' %}  #

{% block body %}
 Home Welcome!
{% endblock %}

最後透過flask route造訪home.html時,會先執行layout.html文件,執行完畢後會帶出home.html內容。我們可以看執行結果如下:








如果你要在layout.html中嵌入其他頁面,可以用{% include '網頁來源' %}這個語法來完成。
<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <title>MyFlaskApp</title></head><body>{% include './includes/menu.html' %}
{% block body %} {% endblock %}
</body></html>

其中menu.html如下:
<a href="https://www.jetbrains.com/pycharm"> pycharm </a> <br><a href="http://flask.pocoo.org/"> flask </a> <br>

執行結果就可以看到layout.html已經嵌入menu.html。



2018年9月24日 星期一

Flask Route

Flask是python網站開發微框架。


File->Setting-選到自己的Project->Project Interpreter-> ┼ (右邊加號)>搜尋flask->install package
  • Flask中的路由
新增一檔案名為app.py,import Flask
#making available the code you need to build web apps with flask
from flask import Flask, render_template
# create an instance of the Flask class for our web app
app = Flask(__name__)


# when the user navigates to localhost:5000, 
# the home function will run and it will return its output on the webpage.
@app.route("/")def hello():
    # return "<h3>Hello World! 123</h3>"
    # 利用render_template()導到html檔案,
    # 要注意的是:1.需import render_template 2.該html檔要放在根目錄的Templates目錄之下    return render_template("home.html")

# If the input to the route method was something else, let’s say ‘/abc/’, 
# the function output would be shown when the user visited localhost:5000/abc/
@app.route("/abc")def hello2():
    return 'Hello World! 45678'

# 執行該application,當debug=True,開發環境中則不必重啟server,重新整理網頁即可
app.run(debug=True) 



點選RUN執行,即可看到結果。