学习日记 | 5.29 [Python3] Python Web开发基础

注:这是一系列基于实验楼网络培训的python学习日记,内容零散,只是便于我自己回顾,有需要请了解www.shiyanlou.com。


3. 实验13: jinja2模板

flask的默认模板通过jinja2实现。

jinja使用一些特殊字符包含需要被解释执行的代码:{%语法语句%} {{python对象}} {#注释#}。 

通过set给jinja赋值变量:

{% set result = heavy_operation() %}

<p> {{ result }}</p>

在jinja2中用macro定义宏,也支持导入宏,如下:

{% from 'macro.html' import course_item %}

<div> {{ course_item(course) }} </div>

模板继承:方便编码共用的标题栏和尾部,继承功能通过block,extends等关键字实现。

示例:

宏 macro.html:

{% macro course_item(course, type="bootstrap") %}
    <div>
        <p> type: {{ type }}</p>
        <p> name: {{course.name }}</p>
        <p> is_private: {{ course.is_private }}</p>
    </div>
{% endmacro %}

须继承的 base.html:

<body>
    <div>
        {% block header %}
            <p> this is header </p>
        {% endblock %}
    </div>
    <div>{% block content %}{% endblock %}</div>
    <div id="footer">
        {% block footer %}
        &copy; Copyright2017 by <a href="http://www.shiyanlou.com/">shiyanlou</a>.
        {% endblock %}
    </div>
</body>

index.html:

<h1> this is the header</h1>

<p> name: {{ course.name }}</p>
<p> user count: {{ course.user_count }}</p>
<p> teacher: {{ course.teacher }}</p>
<p> teacher email: {{ course.teacher.email | hidden_email }}</p>
<p> course tag length: {{ course.tags | length }}</p>
<p> is_private: {{ course.is_private }}</p>
<p> not exist: {{ course.not_exist }}</p>

{% if course.is_private %}
    <p> course {{ course.name }} is private</p>
{% elif course.is_member_course %}
    <p> course {{ course.name }} is member course </p>
{% else %}
    <p> course {{ course.name }} is normal course </p>
{% endif %}

{% for tag in course.tags %}
    <span> {{ tag }} </span>
{% endfor %}

{% macro course_item(course, type="bootstrap") %}
    <div>
        <p> type: {{ type }}</p>
        <p> name: {{ course.name }}</p>
        <p> user count: {{ course.user_count }}</p>
        <p> teacher: {{ course.teacher }}</p>
        <p> is_private: {{ course.is_private }}</p>
    </div>
{% endmacro %}

<div> {{ course_item(course) }}</div>
<p> {{ "=" * 20}}</p>
<div> {{ course_item(course, type="louplus") }}</div>

app.py:

#!/usr/bin/env python3
# -*- coding:utf-8 -*-

from flask import Flask, render_template

app = Flask(__name__)
app.config["TEMPLATES_AUTO_RELOAD"] = True

def hidden_email(email):
    parts = email.split('@')
    parts[0] = "*****"
    return '@'.join(parts)

app.add_template_filter(hidden_email)

@app.route('/')
def index():
    teacher = {
            "name": "tom",
            "email": "[email protected]"
    }
    course = {
            "name": "Python Basic",
            "teacher": teacher,
            "user_count": 5348,
            "price": 199.0,
            "lab": None,
            "is_private": False,
            "is_member_course": True,
            "tags": ['python', 'big data', 'linux']
    }
    return render_template("index.html", course=course)

猜你喜欢

转载自www.cnblogs.com/squidGuang/p/9106973.html