flask笔记:3:模板

来源:互联网 发布:sodu源码 编辑:程序博客网 时间:2024/04/29 17:22
目前的目录结构:
myblog
|----flask
|----tmp
|----app
       |----static
       |----templates
       |----__init__.py
       |----views.py
|----run.py

编写第一个模板
app/templates/index.html
<html>    <title>{{title}} - myblog</title>    <body>        <h1>Hello,{{user.nickname}}</h1>    </body></html>


{{....}}中是变量
{%....%}表达式
会动态从视图模板中获取数据

修改视图模板 app/views.py
from flask import render_templatefrom app import app@app.route('/')@app.route('/index')def index ():    user={'nickname':'Bob'}    return render_template("index.html",    title="Home",    user=user)#从flask导入render_template#render_template(html文件,需要传数据的变量)


模板的判断语句
修改app/templates/index.html
<html>    {% if title %}    <title>{{title}} - myblog</title>    {% else %}    <title>Welcome - myblog</title>    {% endif %}    <body>        <h1>Hello,{{user.nickname}}</h1>    </body></html>


如果删除 app/views.py 中 render_template( ) 函数中title参数
浏览器中的标题就会变成 Welcome - myblog

模板的循环语句
修改 app/views.py
from flask import render_templatefrom app import app@app.route('/')@app.route('/index')def index ():    user={'nickname':'Bob'}    posts=[            {'author':{'nickname':'John'},             'body':'Beautiful day in Portland!'},            {'author':{'nickname':'Susan'},             'body':'The Avengers movie was so cool!'}           ]    return render_template("index.html",    title="Home",    user=user,    posts=posts)


修改 app/templates/index.html
<html>    {% if title %}    <title>{{title}} - myblog</title>    {% else %}    <title>Welcome - myblog</title>    {% endif %}    <body>        <h1>Hello,{{user.nickname}}</h1>        {% for post in posts %}        <p>{{ post.author.nickname }}           says:<b>{{post.body}}</b></p>           {% endfor %}    </body></html>


显示:


模板继承
模板中的固定某部分会多次出现在很多模板中,我们可以单独做成模板,然后让需要的模板中继承

新增一个导航栏模板
app/templates/base.html
<html>    <head>        {% if title %}        <title>{{title}} - myblog</title>        {% else %}        <title>Welcome - myblog</title>        {% endif %}    </head>    <body>        <div>MyBlog:<a href="/index">Home</a></div>        <hr>        {% block content %}        {% endblock%}    </body></html>


{%block content%}
{%endblock%}
这两个表达式之间是新模板可插入的地方

修改 app/templates/index.html
{% extends "base.html" %}{% block content %}<h1>Hello,{{user.nickname}}</h1>{% for post in posts %}<p>{{ post.author.nickname }}says:<b>{{post.body}}</b></p>{% endfor %}{% endblock %}


{%extends 页面%}这是继承模板
{%block content%}
{%endblock%}
这两个表达式之间是可插入内容的地方

显示:


index.html中多了base.html的内容
0 0
原创粉丝点击