【问题标题】:Using Moment.js with Twig将 Moment.js 与 Twig 一起使用
【发布时间】:2012-09-24 07:40:20
【问题描述】:

我正在使用Moment.js 和 Twig 来计算时间前,

代码(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> 

当我尝试在控制台中运行以上字符串时,它运行良好 - '一个月前'。
我不明白为什么 twig 没有给我正确的输出?
难道我做错了什么?。感谢您的宝贵时间。

【问题讨论】:

    标签: javascript twig momentjs


    【解决方案1】:

    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>
    

    【讨论】:

      【解决方案2】:
      <li><p class="created"></p></li>                            
      <script type="text/javascript">
      $(function(){
        $(".created").html(moment.unix({{ post_date_gmt| date('U') }}).local().fromNow());  
      });
      </script>
      

      【讨论】:

        猜你喜欢
        • 2018-07-03
        • 2016-04-03
        • 1970-01-01
        • 1970-01-01
        • 2019-05-23
        • 2013-09-16
        • 2013-04-16
        • 2013-01-13
        • 2014-10-24
        相关资源
        最近更新 更多