Check if a variable is a date with Twig

后端 未结 3 1266
-上瘾入骨i
-上瘾入骨i 2020-12-15 23:02

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

3条回答
  •  攒了一身酷
    2020-12-15 23:25

    You could add a class(my_var) function, for example:

    // src/AppBundle/Twig/HelperExtension.php
    
    namespace AppBundle\Twig;
    
    use Twig_Extension;
    use Twig_SimpleFunction;
    
    class HelperExtension extends Twig_Extension
    {
        public function getFunctions()
        {
            return array(
                new Twig_SimpleFunction('class', array($this, 'getClassName')),
            );
        }
    
        public function getClassName($object)
        {
            if (!is_object($object)) {
                return null;
            }
            return get_class($object);
        }
    }
    

    Usage:

    {% if class(my_var) == 'DateTime' %}
        ...
    {% endif %}
    

提交回复
热议问题