使用jinja2第三方庫(kù)實(shí)現(xiàn) kanado包新增render_template.py
import os
from jinja2 import Environment, FileSystemLoader
def render_template(template_name_or_list, **context):
# 得到放置模板的目錄
path = '{}/templates/'.format(os.getcwd()) # 返回當(dāng)前工作目錄
# 創(chuàng)建一個(gè)加載器,jinja2會(huì)從這個(gè)目錄中加載模板
loader = FileSystemLoader(path)
# 用加載器創(chuàng)建一個(gè)環(huán)境,有了它才能讀取模板文件
env = Environment(loader=loader)
# 調(diào)用get_tempalte()方法加載模板并返回
template = env.get_template(template_name_or_list)
html = template.render(**context)
return html
__init__.py
from .kanado import Kanado
from .render_template import render_template
__all__ = [
Kanado,
render_template
]
app.py
from kanado import Kanado, render_template
app = Kanado(__name__)
@app.route('/')
def home():
'''
主頁(yè)
'''
# 渲染首頁(yè)HTML模板文件
return render_template('home.html')
