duanaoreng9355 2013-01-23 14:34
浏览 47
已采纳

检查变量是否是Twig的日期

I have an array of variables that I want to display in a Twig template and each variable can be either a string or a date.

If the variable is a date, I want to apply the date filter like this:

{{ my_var|date('d/m/Y') }}

And if it's a string I want it to display it the usual way:

{{ my_var }}

Is there any way to test if a variable is a date (ie. an instance of the PHP DateTime object)?

  • 写回答

3条回答 默认 最新

  • douchi8503 2013-01-23 14:42
    关注

    Maybe not the best way to do it, but I found a solution to my problem.

    {% if my_var.timestamp is defined %}
        {{ my_var|date('m/d/Y') }}
    {% else %}
        {{ my_var }}
    {% endif %}
    

    As a DateTime PHP object has a public getTimestamp method, it's a way to check if the variable is a date whether this property is set or not.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?