2、使用Flask-Moment本地化日期和时间

安装 flask-moment

 

 


在templates/base.html中引入moment.js库
Flask-Moment依赖moment.js jquery.js,Bootstrap已经引入了moment.js,现在只需引入moment.js即可

{% extends "bootstrap/base.html" %}

{% block scripts %}
{{ super() }}
{{ moment.include_moment() }}
{% endblock %}

{% block title %}Flasky{% endblock %}

{% block navbar %}
<div class="navbar navbar-inverse" role="navigation">
    <div class="container">
        <div class="navbar-header">
            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                <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="/">Flask</a>
        </div>
        <div class="navbar-collapse collapse">
            <ul class="nav navbar-nav">
                <li><a href="/">Home</a></li>
            </ul>
        </div>
    </div>
</div>
{% endblock %}

{% block content %}
<div class="container">
    <div class="page-header">
    {% block page_content %}{% endblock %}
    </div>
</div>
{% endblock %}

 

引入之后,Flask-Moment向模板开放了moment类,接下来把时间传入模板进行渲染


在hello.py中初始化Flask-Moment,并加入datetime变量

from flask import Flask,request,make_response,redirect,render_template
from flask_bootstrap import Bootstrap
from flask_moment import Moment
from datetime import datetime

app = Flask(__name__)
bootstrap = Bootstrap(app)
moment = Moment(app)


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

@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


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


@app.route('/user/<id>')
def get_user(id):
    user = load_user(id)
    if not user:
        abort(404)
    return '<h1>Hello, %s</h1>' % user.name


if __name__ == '__main__':
    bootstrap.run()
    moment.run()

 


在templates/index.html中使用Flask-Moment渲染时间戳

{% extends "base.html" %}

{% block page_content %}
<p>The local date and time is {{ moment(current_time).format('LLL')}}</p>
<p>That was {{ moment(current_time).fromNow(refresh=True) }}</p>
{% endblock %}

 


时间展示

 

posted @ 2019-10-31 20:08  换头怪  阅读(310)  评论(0编辑  收藏  举报