模板支持是一种替换网页资源内容的一种技术。需要动态的渲染网页中的内容的时候,就需要模板支持功能的支撑。如下属代码所示,对于<h1></h1>
标签中的内容,需要依据不同的请求而在网页中渲染不同的内容,就用到了模板替换的技术,如果不使用模板替换技术,那么这就是一件非常麻烦的事情,对于不同的请求,就需要编写不同的前端代码。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>TemplateReplace</title>
</head>
<body>
<h1>{{ message }}</h1>
<h1>{{ user }}</h1>
</body>
</html>
模板替换的思想是非常简单的,只要通过正则表达式匹配到标签中的{{ }}
的内容,然后利用传递进入模板的值替换之后将模板内容包装成为Response对象返回给客户端即可。
import re
import os
pattern = r"{{(.*?)}}"
def parse_templates(template_content) :
#匹配模板中的{{ }}的内容,如果没有返回元组
compine = re.compile(pattern)
result = compine.findall(template_content)
return result or tuple()
def replace_templates(path,**options) :
#将模板中的内容,替换成传递进来的参数,将替换完之后的内容返回
path = os.path.join('templates',path)
if os.path.exists(path) :
with open(path,"rb") as file :
content = file.read().decode()
parse_contents = parse_templates(content)
if options :
for parse_content in parse_contents :
item = parse_content.strip()
old_value = '{{{{{}}}}}'.format(parse_content)
new_value = str(options.get(item, ''))
content = content.replace(old_value, new_value)
return content
测试用例:
在浏览器中输入http://127.0.0.1:8000/replace 可以看到在浏览器中看到网页渲染内容。
- 传递进上述模板中user = ‘JassonHandler@163.com’ message = 'Hello ,JassonHandler@163.com ’
class TemplateReplaceHandler(BaseHandler) :
def get(self,request,*args,**options):
user = 'JassonHandler@163.com'
message = 'Hello ' + user
return simple_template('template.html',user = user,message = message)
测试反馈 :
2. 传递进上述模板中user = '1797309152@qq.com’message = ‘Hello ,1797309152@qq.com’
测试反馈: