使用jinja2连接模版和py变量
cat get_time.py
import os
from jinja2 import Template
import time
now = (time.strftime("%a %b %d %H:%M:%S %Y", time.localtime()))
def get_time():
with open("date.html", 'r') as f:
data = f.read()
tmp=Template(data)
data=tmp.render(now=now)
print (data)
with open('date_now.html','w') as f:
f.write(str(data.encode("utf-8")))
get_time()
模版定义
cat date.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>now</title>
</head>
<body>
{{ now }}
</body>
</html>
执行get_time.py 获取到新网页
[root@no165 py]# cat date_now.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>now</title>
</head>
<body>
Tue Aug 08 14:41:39 2017
</body>