繁体   English   中英

将Moment.js与Twig一起使用

[英]Using Moment.js with Twig

我正在将Moment.js与Twig一起用于计算时间,

代码(树枝) -
我在post_date_gmt变量中有日期,并且我正在使用它,

<div class="time">
  <time datetime="{{ post_date_gmt| date('Y-m-d H:i:s')}}">moment.unix({{ post_date_gmt }}).local().fromNow()</time>
</div>  

这给我输出:

<div class="time">
    moment.unix(1331845445).local().fromNow()  
</div> 

当我尝试在控制台中在字符串上方运行时,效果很好-“ 一个月前 ”。
我不明白为什么树枝没有给我正确的输出?
难道我做错了什么?。 谢谢你的时间。

moment是一个javascript函数,您正尝试从HTML块而不是javascript块中调用它。 有几种方法可以做到,但是一个简单的技巧就是:

<div class="time">
  <time datetime="{{ post_date_gmt| date('Y-m-d H:i:s')}}">
<script type="text/javascript">document.write(moment.unix({{ post_date_gmt }}).local().fromNow());</script></time>
</div>  

我不建议使用document.write这样。 最好将其作为像这样的单独javascript块来执行(以jquery为例):

<div class="time">
  <time id="time" datetime="{{ post_date_gmt| date('Y-m-d H:i:s')}}"></time>
</div>  

--- snip ---

<script type="text/javascript">
$(function(){
  $('#time').val( moment.unix({{ post_date_gmt }}).local().fromNow() );
});
</script>
<li><p class="created"></p></li>                            
<script type="text/javascript">
$(function(){
  $(".created").html(moment.unix({{ post_date_gmt| date('U') }}).local().fromNow());  
});
</script>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM