user2818060
user2818060

Reputation: 845

Split function not working in Twig

what i Need :

Here is the twig code:

           {%if item.metadata.name |length < 20 %}
            {% set foo = item.metadata.name|split(',') %}

            {{ foo[0] }}

            {%else%}{{WordLimit(item.metadata.name,20,10)}} ..
               {%endif%}

output im getting :

  Deepak Singh.

Upvotes: 0

Views: 944

Answers (1)

griotteau
griotteau

Reputation: 1822

I think the best solution is to write a twig extension. See http://symfony.com/doc/current/cookbook/templating/twig_extension.html

class AcmeExtension extends \Twig_Extension
{
    public function getFilters()
    {
        return array(
            new \Twig_SimpleFilter('first_word', array($this, 'first_word')),
        );
    }

    public function first_word($word)
    {
        $words = explode(' ', $word);
        $first_word = $words[0];
        ...
        return $first_word;
    }

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

And if your twig file :

{{item.metadata.name | first_word }}

Upvotes: 1

Related Questions