1. 程式人生 > >python3+flask 開發web(四)

python3+flask 開發web(四)

1、Janja2模板中程式碼的重複使用,有多種方法:

1)巨集的引用:

首先在專案的目錄下新建templates資料夾,然後在資料夾中新建一個macro.html,內容如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
{% macro render_comment(comment) %}
     <li>{{ comment }}</li>
{% endmacro %}

</body>
</html>

其次在templates資料夾中新建一個for.html,重複使用巨集,內容如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>for_test</title>
</head>
<body>
{% import 'macro.html' as macros%}
<ul>
    {% for comment in comments %}
    {{ macros.render_comment(comment) }}
    {% endfor %}
</ul>
</body>
</html>

Python程式碼如下:

from flask import Flask
from flask import render_template
from flask_script import Manager


app=Flask(__name__)


@app.route('/')
def for_test():
    comments=['navy','luo','123','bnm']
    return render_template('for.html',comments=comments)

if __name__=='__main__':
    app.run()

執行結果如下:

2)重複利用程式碼片段

在common.html的檔案中寫上如下內容:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>我是重複程式碼段</h1>
</body>
</html>

在index01.html中寫上如下內容:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Hello</title>
</head>
<body>
    {% include 'common.html'%}
</body>
</html>

程式碼如下:

from flask import Flask
from flask import render_template

app=Flask(__name__)

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

if __name__ == '__main__':
    app.run()

執行結果:

3)繼承基類模板

新建一個base.html裡面內容如下:

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

新建一個index02.html,內容如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
{% extends 'base.html'%}
{%block title%}
    flask
{%endblock %}
{%block head %}
    {{super()}}
{%endblock %}
{%block body%}
    hello word
{%endblock %}
</body>
</html>

;Python程式碼:

from flask import Flask
from flask import render_template

app=Flask(__name__)

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


if __name__ == '__main__':
    app.run()

執行結果: