Twig:如何检查变量是否为 DateTime 对象

Twig: how to check if a variable is a DateTime object

我必须检查变量是 DateTime对象还是简单的字符串才能在我的模板中使用它。

如果变量是 DateTime,我必须将其格式化为日期;如果是一个字符串,只需打印它。

{% if post.date is DateTime %}
    {% set postDate = post.date|date %}
{% else %}
    {% set postDate = post.date %}
{% endif %}

<p>Il {{ postDate }}

我想我应该使用关于 arrays) 的 Twig Test (as also suggested in this Whosebug 答案来做到这一点,但我不太明白我应该把代码放在我的 Symfony 应用程序的哪个文件夹中以及如何在应用程序中注册它。

编写测试后,如何在 Symfony 的 Twig 模板中使用它?

你应该创建一个 twig 函数

AcmeBundle\Twig\CheckExtension.php

<?php
namespace AcmeBundle\Twig;

class CheckExtension extends \Twig_Extension
{
    public function getFunctions() {
        return array(
            'isDateTime' => new \Twig_Function_Method($this, 'isDateTime'),
        );
    }

    public function isDateTime($date) {
        return ($date instanceof \DateTime); /* edit */
    }

    public function getName()
    {
        return 'acme_check_extension';
    }
}

services.yml

services:
    acme_check_extension:
        class: AcmeBundle\Twig\CheckExtension
        tags:
            - { name: twig.extension }

在您的模板中:

{% if isDateTime(post.date) %} 
    ...
{% endif %}