【问题标题】:Split function not working in Twig拆分功能在 Twig 中不起作用
【发布时间】:2014-09-04 08:05:40
【问题描述】:

我需要什么:

  • 拆分字符串。
  • 我需要字符串中的第一个字符。
  • 如果字符串有一定的字符限制,我喜欢只显示名字而不是(...)。

     ex: ankit mishra pandit aggarwaal.
    
     - so i just want  only ankit.
    
     - if its is ankit mishra its ok.
    
     * otherwise show Full Name.
    

这是树枝代码:

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

            {{ foo[0] }}

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

输出我得到:

  Deepak Singh.

【问题讨论】:

    标签: symfony twig


    【解决方案1】:

    我认为最好的解决方案是编写一个树枝扩展。 见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';
        }
    }
    

    如果你的树枝文件:

    {{item.metadata.name | first_word }}
    

    【讨论】:

    • 谢谢你这是最完美的答案干杯它的工作非常感谢你sr
    猜你喜欢
    • 2014-03-05
    • 2017-09-15
    • 1970-01-01
    • 1970-01-01
    • 2013-05-10
    • 1970-01-01
    • 2018-09-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多