2015-09-07 133 views
6

我有一個自定義函數,我想將其傳遞到刀片模板中。下面是函數:將自定義函數傳遞給Laravel Blade模板

function trim_characters($text, $length = 45, $append = '…') { 

    $length = (int) $length; 
    $text = trim(strip_tags($text)); 

    if (strlen($text) > $length) { 
     $text = substr($text, 0, $length + 1); 
     $words = preg_split("/[\s]| /", $text, -1, PREG_SPLIT_NO_EMPTY); 
     preg_match("/[\s]| /", $text, $lastchar, 0, $length); 
     if (empty($lastchar)) 
      array_pop($words); 

     $text = implode(' ', $words) . $append; 
    } 

    return $text; 
} 

而且用法是這樣的:

$string = "A VERY VERY LONG TEXT"; 
trim_characters($string); 

是否可以通過自定義功能的刀片模板?謝謝。

回答

18

您不必通過什麼刀片。如果你定義你的功能,你可以從刀片中使用它。


  1. 創建一個新的文件app/helpers.php
  2. 將您的trim_characters函數添加到它。
  3. Add that file to your composer.json file
  4. 運行composer dump-autoload

現在只需直接使用功能的刀片:

{{ trim_characters($string) }} 
+0

它的工作原理。謝謝。 – FewFlyBy

+1

不適用於我。我得到'調用未定義的函數'並且函數在頁面頂部以純文本打印!? – MattClimbs

+0

適合我的作品。謝謝。 – KickingLettuce