2015-04-17 51 views
0

使用這個枝杈模板不工作:嫩枝「微調」預期

{% for line in lines%} 
    {{line}} after trim('.php') is: {{line|trim('.php')}}<br> 
{% endfor %} 

在Silex的使用控制器使上面的模板:

$app->get('/try', function() use ($app) 
{ 
    $lines=[]; 
    $lines[]='123.php'; 
    $lines[]='news.php'; 
    $lines[]='map.php'; 

    return $app['twig']->render('try.html.twig', ['lines'=>$lines]); 
} 
    ); 

我收到以下輸出:

123.php after trim('.php') is: 123 
news.php after trim('.php') is: news 
map.php after trim('.php') is: ma 

注意最後修剪:map.php應該變成map,但現在是ma

回答

4

我認爲這是預期的行爲。

trim()不修剪子字符串,而是修改字符列表。

所以:

map.php after trim('.php') is: ma 

map.php -> does it start/end with any of ['.php'] -> TRUE -> map.ph 
map.ph -> does it start/end with any of ['.php'] -> TRUE -> map.p 
map.p -> does it start/end with any of ['.php'] -> TRUE -> map. 
map. -> does it start/end with any of ['.php'] -> TRUE -> map 
map  -> does it start/end with any of ['.php'] -> TRUE -> ma 
ma  -> does it start/end with any of ['.php'] -> FALSE -> ma 

它的作用完全一樣:php's trim()

希望這有助於。

+0

很好的解釋。謝謝。 – TaylorR

2

修剪(與實際的PHP函數一樣)使用參數(或常規PHP中的第二個參數)作爲字符映射而不是字符串。

這個說法可以更好地解釋爲a list of characters that, if found in any order, will be trimmed from the beginning or end of the given string

5

根據其他列出的答案,你錯誤地解釋了Twig的trim函數是如何工作的(它使用參數作爲字符映射)。

什麼你可能尋找的是replace過濾器來代替:

{% for line in lines %} 
    {{ line }} after replace({'.php': ''}) is: {{ line|replace({'.php': ''}) }}<br> 
{% endfor %} 
+0

這解決了我的問題。我正在使用替換。但是正確的語法是這樣的:'line | replace({'。php':''})' – TaylorR