Python Flask学习_使用Flask-Moment

为了解决时间本地化的问题,解决的方法是:服务器把时间发送给Web浏览器,浏览器将时间转化为本地时间,然后再渲染模板,进行显示。

moment.js是使用JavaScript开发的优秀客户端开源代码库,它可以在浏览器中渲染日期和时间 。

Flask-Moment是一个Flask程序扩展,能把moment.js集成到Jinja2模板中 。

一、安装和初始化Flask-moment

#   pyCharm Terminal                    #安装flask-moment

pip install flask-moment
#  test.py

from flask_moment import Moment        #引入
moment = Moment(app)                   #初始化:app是Flask实例(app = Flask(__name__))

二、在html文档中引入moment.js

实际上 ,Flask-moment依赖于jquery.js和moment.js两个库,但是jquery.js在bootstrap中已经引入(base.html是继承自bootstrap/base.html的),因此只需要 在引入moment.js,就可以在html文档中使用了。

#   base.html

{% block scripts %}                            
{{ super() }}
{{ moment.include_moment() }}                        #引入moment.js
{% endblock %}

三、在html文档中使用moment.js

{% block content %}
<div class="container">
    <div class="page-header">
        <h1>Hello, {{ name }}!</h1>
    </div>
    <p>The local date and time is {{ moment(current_time).format('LLL') }}.</p>
    <p>That was {{ moment(current_time).fromNow(refresh=True) }}</p>
</div>
{% endblock %}

Flask-Moment想模板(html文档)开放了moment类。就可以像使用普通类那样使用moment。

但是,还需要从.py文件中传入current_time变量

四、传入html文档需要的变量

# test.py

@app.route("/")
def index():
    return render_template('index.html',name='Jack',current_time=datetime.utcnow())       #向模板中current_time传入datetime.utcnow()

五、运行效果








猜你喜欢

转载自blog.csdn.net/bird333/article/details/80722395