码迷,mamicode.com
首页 > 其他好文 > 详细

flask笔记:3:模板

时间:2016-05-12 15:08:38      阅读:198      评论:0      收藏:0      [点我收藏+]

标签:

目前的目录结构:
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_template
from 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_template
from 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的内容

flask笔记:3:模板

标签:

原文地址:http://blog.csdn.net/u013055678/article/details/51365740

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!