如何继承jinja模板

1. be clear to what you are expecting : 我想知道如何在jinja2中实现模板继承

首先要了解,block的概念,官网给了很清晰的解释:

All the block tag does is tell the template engine that a child template may override those placeholders in the template.

2.父模板中的代码:

 

{%block title%}<p> this will appear if the lunchbox.html does nothing</p> {%endblock%}
{%block description%} <p> this will appear if the lunchbox.html does nothing</p> {%endblock%}

子模板中的代码:

 

{% extends "/Users/WildChaser/EurekaMatata/Lunchbox/templates/homepage.html" %}
{%block title%}
{{title}}
{%endblock%}

{%block description%}
{{description}}
{%endblock%}

 

3.注意点:子模板对父模板的block不过是起到一个override的作用。

4.父模板是个request,子模板其实是response的内容,那么web服务器的可视函数要怎么写呢?

jinja2的生命周期:先创建加载器,再创建envrionment对象,最后创建template对象。

@app.route('/test',methods=['POST'])
def helloworld():
templateLoader = jinja2.FileSystemLoader(searchpath="/")
templateEnv = jinja2.Environment(loader=templateLoader)

TEMPLATE_FILE = "/Users/WildChaser/EurekaMatata/Lunchbox/templates/lunchbox2.html"
template = templateEnv.get_template(TEMPLATE_FILE)

dbc = Dbc.Dbc()
result = dbc.selectAllMeal()
dbc.closeDB()

jfile = json.dumps(result)

templateVars = {"title": jfile,
"description": "A simple inquiry of function.",
}

outputText = template.render(templateVars)
return outputText

 





posted @ 2016-10-04 20:53  zoehuang  阅读(289)  评论(0编辑  收藏  举报