Check if a variable is a date with Twig

后端 未结 3 1265
-上瘾入骨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:20

    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.

    0 讨论(0)
  • 2020-12-15 23:20

    Michael's solution works in most cases, but there are some special cases you should consider when you want to have a universal solution.

    First, an object that you test for having a getTimestamp() method doesn't have to be a DateTime instance. I can thing of many cases when the timestamp field would be useful in an object, so I would test the getTimezone() method instead.

    Second, if my_var is an object having a magic __call method defined, then all such tests would turn out positive. That's why I suggest the following negative test:

    {% if my_var.timezone is defined and my_var.nonExistingProperty is not defined %}
        {{ my_var|date('m/d/Y') }}
    {% else %}
        {{ my_var }}
    {% endif %}
    

    The second case was the one I recently struggled with because of using Propel ORM objects. The base class has the __call method that catches all Twig is defined tests.

    0 讨论(0)
  • 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 %}
    
    0 讨论(0)
提交回复
热议问题