moment.js客户端开源代码库,可以在浏览器中渲染日期和时间。Flask-Moment是一个flask程序扩展,能把moment.js集成到Jinja2模板中。

 

1、安装

pip install flask-moment

 

2、初始化Flask-Moment

from flask_moment import Moment

moment = Moment(app)

除了moment.js,Flask-Moment还依赖jQuery.js。安装了flask-bootstrap(pip install flask-bootstrap),由于Bootstrap已经引入了jQuery.js,因此只需引入moment.js即可。

 

3、template/base.html:引入moment.js库

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

 

4、hello.py:加入一个datetime变量

from datetime import datetime

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

 

5、templates/index.html: 使用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>

注:可查阅文档(http://momentjs.com/docs/#/displaying/)学习moment.js提供的全部格式化选项。

 

6、结果截图

 

posted on 2017-01-21 11:20  当太阳不再发光  阅读(1050)  评论(0编辑  收藏  举报