简体   繁体   English

将Moment.js与Twig一起使用

[英]Using Moment.js with Twig

I am using Moment.js with Twig for calculating Time ago, 我正在将Moment.js与Twig一起用于计算时间,

Code (Twig) - 代码(树枝) -
I have date in post_date_gmt variable and i am using it like, 我在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>  

This give me output : 这给我输出:

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

When i try to run above string in console it worked fine - ' a month ago '. 当我尝试在控制台中在字符串上方运行时,效果很好-“ 一个月前 ”。
I don't understand why twig is not giving me the correct output? 我不明白为什么树枝没有给我正确的输出?
Am i doing something wrong?. 难道我做错了什么?。 Thanks for your time. 谢谢你的时间。

moment is a javascript function and you're trying to call it from a block of HTML instead of a block of javascript. moment是一个javascript函数,您正尝试从HTML块而不是javascript块中调用它。 There are several ways you could do it, but an easy hack would be: 有几种方法可以做到,但是一个简单的技巧就是:

<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>  

I don't recommend using document.write like that though. 我不建议使用document.write这样。 It would be better to do this as a separate block of javascript sort of like this (using jquery as an example): 最好将其作为像这样的单独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