Flask学习总结笔记(3)-- Jinja2模板引擎之一

在MVC架构中,使用模板实现页面的设计与布局是一种非常常见的方式,比如PHP的smarty、J2ee的Freemarker和velocity、.NET的velocity.net等。Jinja2是基于python的模板引擎,具有相似的功能,完全支持unicode,具有集成的沙箱执行环境,应用广泛。

0x01 原始方式

在前面的hello world程序中,我们只是简单返回了一个字符串,但是在Web应用中,我们应该遵循HTML规范,比如我们需要返回一个如下HTML页面:


<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Testtitle>
head>
<body>
<h1>Testh1>
body>
html>

修改views.py代码如下:

#!flask/bin/python
#coding:utf-8

__author__ = 'kikay'

from app import app

@app.route('/')
@app.route('/index')
def index():
    html='''
    
    
        
            
            Test
        
        
            

Test

'''
return html

效果如下:

Flask学习总结笔记(3)-- Jinja2模板引擎之一_第1张图片

上面的方式非常繁琐,在Python代码中还要注意做好嵌入的HTML代码的格式和转义等等。现在我们在app包文件夹下新建一个templates文件夹,然后在templates文件夹下新建一个firstone.html文件,内容就是我们需要输出的html代码,函数index直接去读取其中的内容,然后输出。views.py如下:

#!flask/bin/python
#coding:utf-8

__author__ = 'kikay'

from app import app

@app.route('/')
@app.route('/index')
def index():
    with open('app/templates/firstone.html','r') as f:
        html=f.read()
    return  html

注意文件路径的问题,这里的路径应该是相对于run.py的路径。

0x02 使用模板

上面第2种方式就是使用模板的雏形。直接看下面的例子(文件app/templates/index.html):


<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>{{title}}title>
head>
<body>
<h1>hello,{{author.name}}h1>
body>
html>

{{…}}就像是一个占位符,可以将.py中输出的参数“替换”到{{…}}的内容。views.py的代码如下:

#!flask/bin/python
#coding:utf-8

__author__ = 'kikay'

from app import app
from flask import render_template

@app.route('/')
@app.route('/index')
def index():
    author={
        'name':'kikay',
        'age':24
    }
    return render_template('index.html',
                           author=author,
                           title='Welcome')

效果如下:

Flask学习总结笔记(3)-- Jinja2模板引擎之一_第2张图片

需要注意的是,如果模板中的{{…}}中的参数在调用的函数中没有定义的话,那么直接替换为空。

在下一篇博客中将总结Jinja2模板引擎的特征与使用方法。

你可能感兴趣的:(Flask)