2014-09-03 164 views
0

選擇第一個字符串,我需要什麼:如何嫩枝

  • 我從字符串只需要名字。

    Like String : Bodo Jorg Udo .. (i have .. notation if string of length is more then 20). 
    

    這裏是源代碼

     {%if item.metadata.name |length < 20 %} 
         {{item.metadata.name}} 
         {%else%}{{WordLimit(item.metadata.name,10,10)}} .. 
          {%endif%} 
    

    輸出應該像

    Bodo 
    

回答

2

你可以用嫩枝的拆分過濾器相匹配的空白字符。它會返回一個包含分割字符串的數組。

New in version 1.10.3: The split filter was added in Twig 1.10.3. 
The split filter splits a string by the given delimiter and returns a list of strings: 

{% set foo = "one,two,three"|split(',') %} 
{# foo contains ['one', 'two', 'three'] #} 

在你的情況,你會想在嫩枝文檔的Split page一個空白| split(' ')

更多信息以取代逗號。

+0

拆分後的廣告d第一個過濾器,它會給你你的名字。 '{%set yourVariable = yourString | split('')| First()%}' – kodvin 2014-09-08 13:53:32

0

我想你是從文本擴展名中尋找截斷過濾器。 http://twig.sensiolabs.org/doc/extensions/text.html

您可以通過添加這樣的服務定義進行配置:

services: 
twig.extension.text: 
    class: Twig_Extensions_Extension_Text 
    tags: 
     - { name: twig.extension } 

那麼你可以申請過濾器:

{{ item.metadata.name|truncate(10) }} 

過濾器有一些爭論,而且重要的一個因爲你是分隔符值(默認情況下它的「...」,這是你想要的值,如果字符串多於10個字符)