Question

I know that there were similar questions here, but they didn't help me.

In the main py file I just set the global variable named nowts as follows:

app.jinja_env.globals['nowts'] = datetime.datetime.now()

And in the main (base) template (base.html file) I just pass and formatting datetime as follows:

{% block navbar %}
... 
<p>{{ nowts.strftime('%A, %b %d %Y / %X') }}</p>
...
{% endblock %}

For example, output is:

Wednesday, Mar 26 2014 / 11:57:51

As you see date and time are displayed correctly, but only once. After a few minutes I re-open the main page (or subpages) and the time is still the same. How to update the nowts global variable always if the user refreshes the page?

Was it helpful?

Solution

Use a context processor to inject values per request:

@app.context_processor
def inject_template_globals():
    return {
        'nowts': datetime.datetime.utcnow(),
    }

You generally want to use UTC time, not local time, for web servers. You never know where in the world your request comes from.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top