You are here

public function TwigText::truncate in Bamboo Twig 8.4

Same name and namespace in other branches
  1. 8.5 bamboo_twig_extensions/src/TwigExtension/TwigText.php \Drupal\bamboo_twig_extensions\TwigExtension\TwigText::truncate()
  2. 8.2 bamboo_twig_extensions/src/TwigExtension/TwigText.php \Drupal\bamboo_twig_extensions\TwigExtension\TwigText::truncate()
  3. 8.3 bamboo_twig_extensions/src/TwigExtension/TwigText.php \Drupal\bamboo_twig_extensions\TwigExtension\TwigText::truncate()

Truncate a string.

Can't use the Twig filter callback cause the truncate function is actually declared as a global function and not method of Twig_Extensions_Extension_Text.

Parameters

\Drupal\Core\Template\TwigEnvironment $env: A Twig_Environment instance.

string $string: The input string. Must be one character or longer.

int $length: The string returned will contain at most length chars from beginning.

bool $preserve: Preserving whole words or not.

string $separator: The ellipsis to use.

Return value

string|bool Returns the extracted part of string; or FALSE on failure, or an empty string.

File

bamboo_twig_extensions/src/TwigExtension/TwigText.php, line 52

Class

TwigText
Provides bridge for Text functions and filters.

Namespace

Drupal\bamboo_twig_extensions\TwigExtension

Code

public function truncate(TwigEnvironment $env, $string, $length = 30, $preserve = FALSE, $separator = '...') {
  $extension = new \Twig_Extensions_Extension_Text();
  $filters = $extension
    ->getFilters();
  foreach ($filters as $filter) {
    if ($filter
      ->getName() == 'truncate') {
      $callable = $filter
        ->getCallable();
      return $callable($env, $string, $length, $preserve, $separator);
    }
  }
  return FALSE;
}