模板是一个包含响应文本的文件,其中包含用占位变量表示的动态部分,其具体值只会在请求上下文中才能被具体赋值。
定义index.html和user.html
index.html
<h1>Hello!h1>
user.html
<h1>Hello,{{name | capitalize}}h1>
渲染模板
默认情况下,flask在项目根目录的templates子文件夹中寻找模板
from flask import Flask,render_template
app=Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/user/' )
def user(name):
return render_template('user.html',name=name)
url中携带的参数name会被传入user.html渲染
在模板中使用其他变量继续定义字典、列表、类,并在模板中渲染出来
python中的对象要在调用render_template渲染页面时传过去才能被前端识别到
修改temp.py:
class Person:
def __init__(self,pname,page):
self.name=pname
self.age=page
def get_info(self):
return "name:%s,age:%s" % (self.name,self.age)
mydict = {'0': 'apple', '1': 'banana'}
myint = 1
mylist = ['alex', 'bob']
p = Person('leon', '23')
@app.route('/user/' )
def user(name):
return render_template('user.html',name=name,mydict=mydict,myint=myint,mylist=mylist,p=p)
修改user.html:
<p>value of dict:{{mydict['1']}}p>
<p>value of list:{{mylist[0]}}p>
<p>value of list:{{mylist[myint]}}p>
<p>value of list:{{p.get_info()}}p>
Jinja2中的控制结构
<h1>控制结构h1>
{% if user %}
Hello,{{ user }}!
{% else %}
Hello,stranger!
{% endif %}
Jinja2中的循环结构
<h1>循环结构h1>
<ul>
{% for i in mylist %}
<li>{{i}}li>
{% endfor %}
ul>
效果:
定义宏macros.html:
{% macro render_comment(comment) %}
<li>{{comment}}li>
{% endmacro %}
<ul>
{% for comment in comments %}
<li>{{render_comment(comment)}}li>
{% endfor %}
ul>
使用宏:
<h1>使用宏h1>
{% import 'macros.html' as macros %}
<ul>
{% for i in mylist %}
<li>{{macros.render_comment(i)}}li>
{% endfor %}
ul>
Jinja2模板继承
base.html,block标签定义的元素可在衍生模板中修改,这里定义了head、title、body三个块
<html>
<head>
{% block head %}
<title>
{% block title %}
{% endblock %}
My App
title>
{% endblock %}
head>
<body>
{% block body %}
{% endblock %}
body>
html>
extends.html继承base.html,基模板中的3个块被重新定义。
需要调用super()方法,这一点和python中的类继承类似
{% extends "base.html" %}
{% block title %}Extends{% endblock %}
{% block head %}
{{super()}}
<style>style>
{% endblock %}
{% block body %}
<h1>Template Extendsh1>
{% endblock %}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)