Python Jinja2模块简单使用

1、新建一个jinja2模板

<html>
<head></head>
<body>

<h1>{{title}}</h1>
<p>My name is : {{name | title}}</p>
<p>My age is : {{age}}</p>
<p>My loc is : {{loc | title}}</p>

</body>
</html>

2、新建一个Python脚本调用jinja2模块并对其进行简单封装

import jinja2
import os
import webbrowser

"""实用系统路径来创建一个获取jinja2模板内容的函数"""
def render(tplPath,**kvargs):
	"""跨平台相关设置"""
    if os.name == 'nt':
        currPath = '.\\'
    else:
        currPath = './'

    path,fileName = os.path.split(tplPath)
    return jinja2.Environment(
        loader=jinja2.FileSystemLoader(path or currPath)
    ).get_template(fileName).render(**kvargs)

"""获取content"""
def getContent():
    title = 'TestTitle'
    name = 'lissen'
    age = 12
    loc = 'beijing'
    localDict = locals()

	"""使用**kvargs来封装本地参数到localDict,并在render函数中调用"""
    content = render('.\\test.html',**localDict)
    return content
    
"""创建一个函数来立即显示到浏览器"""
def showWeb(fileName):
    with open(fileName,'w') as fObj:
        fObj.write(getContent())
        fObj.close()

    webbrowser.open(fileName,new=1)

if __name__ == '__main__':
	showWeb('testJinJa2.html')

Web页面显示结果如下:
在这里插入图片描述

发布了20 篇原创文章 · 获赞 24 · 访问量 2587

猜你喜欢

转载自blog.csdn.net/u011285708/article/details/104333198