Flask从零单排-2.渲染模板

本文介绍了Flask使用Jinja2模板引擎进行渲染的方法,包括创建templates文件夹,导入render_template模块,以及如何渲染index.html和user.html。还讲解了变量过滤器如capitalize和title,条件控制语句,以及模板继承的概念,提供了base.html作为基模板的示例。
摘要由CSDN通过智能技术生成

渲染模板

Flask使用了一个名为Jinja2的强大模板引擎。

templates/index.html

<h1>Hello, world!</h1>

templates/user.html

<h1>Hello, {{ name }}!</h1> 
{{ name }}结构表示一个变量,它告诉模板引擎这个位置的值可以从模板渲染时使用的数据中获取

在渲染模板之前需要把index.html和user.html存放在根目录下的templates文件夹下,如果没有就创建一个
还需要在python里导入模块,render_template

hello.py 渲染模板

from flask import Flask, render_template
app = Flask(__name__)

# 首页
@app.route('/')
def index():
    return 'Hello ,world!'

# 动态URL规则
@app.route('/user/<name>')
def user(name):
    return "Hello, %s" % name

# 渲染模板
@app.route('/template/hello/')
def hello():
    return render_template('index.html')

@app.route('/template/<name>')
def template_user(name):
    return render_template('user.html', name=name)


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

运行程序后在浏览器里分别输入http://127.0.0.1:5000/template/hello/http://127.0.0.1:5000/template/Flask

模板hello.jpg

模板user.jpg

变量过滤器

就说几个常用的
capitalize 把值的首字母转换成大写,其他字母转化成小写
title 把值中每个单词的首字母都转换成大写

条件控制语句

<h1>{% if name %}
    Hello, {{ name }}!
    {% else %}
    Hello, flask!
    {% endif %}!
</h1>

模板继承

基模板base.html
templates/base.html

<html>
    <head>
        {% block head %}
        <title>
            {% block title %}{% endblock %} - My application
        </title>
    </head>
    {% endblock%}
</html>

调用基模板
templates/user.html

{% extends "base.html" %}

{% block title %}aaa{% endblock %}

调用基模板后URL.jpg

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值