我有一个 Flask 生成的时间值列表,格式如下:YYYY-DD-MM hh:mm:ss。这些时间值用作 url 链接,并使用 jinja2 显示在我的 html 文件中,如下所示:
{% for job in jobs %} <a href=”{{ url_for(‘jobs/by_id’,job_id=job.job_id) }}"> {{ job.finishtime }} #this is the time value </a> {% endfor %}
我希望这些时间值自动转换为浏览器的本地时区。我尝试使用 flask-moment 扩展,但在遵循所有说明并使用 {{ moment(job.finishtime).format('MMMM Do YYYY, h:mm:ss a') }}
后,当我加载它时,时间从 html 页面消失。我也尝试了其他力矩函数,但一直出错。
有没有更好的方法让 moment.js 与我的 jinja 代码对话?
我希望不必处理 python 日期时间。
最佳答案
不幸的是,Jinja2 是在服务器上呈现的,所以它的代码永远不会在客户端的机器上运行——它不能(轻易地)掌握时区。
这意味着 Javascript 在 Jinja2 模板呈现后运行,因此您不能在 jinja2 标签内使用 JS。
有几种方法可以解决这个问题/解决您的问题:
1) 当用户第一次访问您的站点(或登录,如果可能的话)时,让一些 javascript 设置一个 timezone
cookie。然后可以在服务器端读取它,并将其传递到模板中 - 如下所示:
# On the server
def view_jobs_page(request, response):
import datetime
tz = datetime.timedelta(seconds = int(request.cookies["timezone"])) # Pass this into the Jinja2 render function
# ... Do stuff
# In your template
local time: {{ job.finishtime + tz }}
如果不知道您正在使用的确切堆栈和代码结构,就很难给出更详细的示例。这也有使用 datetime
的缺点,这是您不想要的。
2) 使用 javascript 应用时间增量:
<!-- In the head -->
<script>
// When the page loads - the Jinja template is already rendered now
window.onload = function() {
// Get all the elements with the given class, and map through them
document.querySelectorAll(".datetime_to_be_adjusted").forEach(function(el){
var utcTime = moment.utc(el.innerText); // This is the time in UTC
utcTime.local(); // Switch to using the browser's local timezone
el.innerText = utcTime.format('MMMM Do YYYY, h:mm:ss a'); // Write the local time back to the element
});
}
</script>
...
{% for job in jobs %}
<a href=”{{ url_for(‘jobs/by_id’,job_id=job.job_id) }}" class="datetime_to_be_adjusted">
{{ job.finishtime }}
</a>
{% endfor %}
这当然依赖于页面中包含的 momentJS,并使用它的 UTC parsing mechanis .
关于javascript - 如何在页面加载时将 jinja 代码中的时间值转换为浏览器的本地时区?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32598735/