python使用jinja2

模板test.html

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

<h1>{
   
   {title}}</h1>
<p>My name is : {
   
   {name}}</p>
<p>My age is : {
   
   {age}}</p>
<p>My loc is : {
   
   {loc}}</p>
{% for n in list %}
	{
   
   {n.key}}
{% endfor %}
</body>
</html>

代码

import jinja2
import os

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)


def getContent():
	title = 'mytest'
	name = 'nxy'
	age = 18
	loc = 'beijing'
	list = [{'key':'one'},{'key':'two'},{'key':'three'}]
	localDict = locals()

	content = render('test.html',**localDict)
	return content
	

def writefile(fileName):
	with open(fileName,'w') as fObj:
		fObj.write(getContent())
		fObj.close()


if __name__ == '__main__':
	writefile('testjinja2.html')

生成文件testjinja2.html

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

<h1>mytest</h1>
<p>My name is : nxy</p>
<p>My age is : 18</p>
<p>My loc is : beijing</p>

        one

        two

        three

</body>
</html>

猜你喜欢

转载自blog.csdn.net/woailp___2005/article/details/111572895