- Flask Framework Cookbook(Second Edition)
- Shalabh Aggarwal
- 162字
- 2021-06-24 13:58:03
How to do it...
To use Moment.js in an application, please follow the required steps:
First, write a wrapper in Python and use it via the jinja environment variables, as follows:
from jinja2 import Markup class momentjs(object): def __init__(self, timestamp): self.timestamp = timestamp # Wrapper to call moment.js method def render(self, format): return Markup("<script>\ndocument.write(moment(\"%s\").%s)
;\n</script>" % (self.timestamp.strftime("%Y-%m-
%dT%H:%M:%S"), format)) # Format time def format(self, fmt): return self.render("format(\"%s\")" % fmt) def calendar(self): return self.render("calendar()") def fromNow(self): return self.render("fromNow()")
You can add as many Moment.js methods as you want to parse to the preceding class, as and when they're needed. Now, in your app.py file, set the following created class to the jinja environment variables:
# Set jinja template global app.jinja_env.globals['momentjs'] = momentjs
You can now use the class in templates, as shown in the following example. Make sure that the timestamp is an instance of a JavaScript date object:
<p>Current time: {{ momentjs(timestamp).calendar() }}</p> <br/> <p>Time: {{momentjs(timestamp).format('YYYY-MM-DD HH:mm:ss')}}</p> <br/> <p>From now: {{momentjs(timestamp).fromNow()}}</p>