flask web development Chapter03

Templates

The Jinja2 Template Engine

templates/index.html: Jinja2 template

<h1>Hello World!</h1>

templates/user.html: Jinja2 template

<h1>Hello, {{ name }}!</h1>

Rendering Templates

from flask import Flask, render_template
# ...
@app.route('/index')
def index():
  return render_template('index.html')

@app.route('/user/<name>')
def user(name):
  return render_template('user.html', name=name)

Variables

Jinja2 recognizes variables of any type, even complex types such as lists, dictionaries and objects. The following are some more examples of variables used in templates:

<p>A value from a dictionary: {{ mydict['key'] }}.</p>
<p>A value from a list: {{ mylist[3] }}.</p>
<p>A value from a list, with a variable index: {{ mylist[myintvar] }}.</p>
<p>A value from an object's method: {{ myobj.somemethod() }}.</p>
Filter name DescriptionDescription
safeRenders the value without applying escaping
capitalizeConverts the first character of the value to uppercase and the rest to lowercase
lowerConverts the value to lowercase characters
upperConverts the value to uppercase characters
titleCapitalizes each word in the value
trimRemoves leading and trailing whitespace from the value
striptagsRemoves any HTML tags from the value before rendering

Such as:

Hello, {{ name|capitalize }}

Control Structures

{% if user %}
  Hello, {{ user }}!
{% else %}
  Hello, Stranger!
{% endif %}
<ul>
  {% for comment in comments %}
    <li>{{ comment }}</li>
  {% endfor %}
</ul>
{% macro render_comment(comment) %}
  <li>{{ comment }}</li>
{% endmacro %}
<ul>
  {% for comment in comments %}
    {{ render_comment(comment) }}
  {% endfor %}
</ul>
{% import 'macros.html' as macros %}
<ul>
  {% for comment in comments %}
    {{ macros.render_comment(comment) }}
  {% endfor %}
</ul>

Twitter Bootstrap Integration with Flask-Bootstrap

(venv) $ pip install flask-bootstrap
from flask.ext.bootstrap import Bootstrap
# ...
bootstrap = Bootstrap(app)

templates/base.html

<div>
    {% extends "bootstrap/base.html" %}
</div>
<div>
    {% block title %}Flasky{%endblock%}
</div>
<div>
    {%block navbar%}
</div>
<div class="container">
    <nav class="navbar navbar-default">
        <div class="container-fluid">
            <div class="navbar-header">
                <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
            <span class="sr-only">Toggle navigation</span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
        </button>
                <a class="navbar-brand" href="#">Flasky</a>
            </div>
            <div id="navbar" class="navbar-collapse collapse">
                <ul class="nav navbar-nav">
                    <li class="active"><a href="/">Home</a></li>
                    <li><a href="#">Abourt</a></li>
                    <li><a href="#">Contact</a></li>
                    <li class="dropdown">
                        <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="flase">
                        Dropdown
                        <span class="caret"><span></a>
                        <ul class="dropdown-menu">
                            <li><a href="#">Action</a></li>
                            <li><a href="#">Another action</a></li>
                            <li><a href="#">Something else here</a></li>
                            <li role="separator" class="divider"></li>
                            <li class="dropdown-header">Nav header</li>
                            <li><a href="#">Separated link</a></li>
                            <li><a href="#">One mor separated link</a></li>
                        </ul>
                    </li>
                </ul>
                <ul class="nav navbar-nav navbar-right">
                    <li class="active"><a href="#">Default
                    <span class="sr-only">(current)</span></a>
                    </li>
                    <li><a href="#">Static top</a></li>
                    <li><a href="#">Fixed top</a></li>
                </ul>
            </div>
        </div>
    </nav>
</div>
<div>
    {%endblock%}
</div>
<div>
    {%block content%}
</div>
<div class="container">
    {% block page_content %} {% endblock %}
</div>
<div>
    {%endblock%}
</div>

templates/index.html

<div>
    {% extends "base.html" %}
</div>
<div>
    {% block title %}Flasky{%endblock%}
</div>
{% block page_content %}
<div class="page-header">
    <h1>Hello world!!!</h1>
</div>

templates/user.html

<div>
    {% extends "base.html" %}
</div>
<div>
    {% block title %}Flasky{%endblock%}
</div>
{% block page_content %}
<div class="page-header">
    <h1>Hello , {{ name }} !</h1>
</div>
{% endblock %}

Flask-Bootstrap’s base template blocks

Blockname Description
docThe entire HTML document
html_attribsAttributes inside the html tag
htmlThe contents of the html tag
headThe contents of the head tag
titleThe contents of the title tag
metasThe list of meta tags
stylesCascading stylesheet definitions
body_attribsAttributes inside the body tag
bodyThe contents of the body tag
navbarUser-defined navigation bar
contentUser-defined page content
scriptsJavaScript declarations at the bottom of the document

hello.py: Custom error pages

@app.errorhandler(404)
def page_not_found(e):
  return render_template('404.html'), 404

@app.errorhandler(500)
def internal_server_error(e):
  return render_template('500.html'), 500

templates/base.html: favicon definition

{% block head %}
{{ super() }}
<link rel="shortcut icon" href="{{ url_for('static', filename = 'favicon.ico') }}"
type="image/x-icon">
<link rel="icon" href="{{ url_for('static', filename = 'favicon.ico') }}"
type="image/x-icon">
{% endblock %}

Localization of Dates and Times with Flask-Moment

(venv) $ pip install flask-moment

hello.py: Initialize Flask-Moment
from flask.ext.moment import Moment moment = Moment(app)
hello.py: Add a datetime variable

from datetime import datetime
@app.route('/')
def index():
  return render_template('index.html',
    current_time=datetime.utcnow())

templates/base.html: Import moment.js library
{% block scripts %} {{ super() }} {{ moment.include_moment() }} {% endblock %}

  • templates/index.html: Timestamp rendering with Flask-Moment*
<p>The local date and time is {{ moment(current_time).format('LLL') }}.</p>
<p>That was {{ moment(current_time).fromNow(refresh=True) }}</p>

转载于:https://www.cnblogs.com/keer2345/p/6037773.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值