3 namespace Drupal\twig_extension_test\TwigExtension;
6 * A test Twig extension that adds a custom function and a custom filter.
8 class TestExtension extends \Twig_Extension {
11 * Generates a list of all Twig functions that this extension defines.
14 * A key/value array that defines custom Twig functions. The key denotes the
15 * function name used in the tag, e.g.:
20 * The value is a standard PHP callback that defines what the function does.
22 public function getFunctions() {
24 'testfunc' => new \Twig_Function_Function(['Drupal\twig_extension_test\TwigExtension\TestExtension', 'testFunction']),
29 * Generates a list of all Twig filters that this extension defines.
32 * A key/value array that defines custom Twig filters. The key denotes the
33 * filter name used in the tag, e.g.:
35 * {{ foo|testfilter }}
38 * The value is a standard PHP callback that defines what the filter does.
40 public function getFilters() {
42 'testfilter' => new \Twig_Filter_Function(['Drupal\twig_extension_test\TwigExtension\TestExtension', 'testFilter']),
47 * Gets a unique identifier for this Twig extension.
50 * A unique identifier for this Twig extension.
52 public function getName() {
53 return 'twig_extension_test.test_extension';
57 * Outputs either an uppercase or lowercase test phrase.
59 * The function generates either an uppercase or lowercase version of the
60 * phrase "The quick brown fox jumps over the lazy dog 123.", depending on
61 * whether or not the $upperCase parameter evaluates to TRUE. If $upperCase
62 * evaluates to TRUE, the result will be uppercase, and if it evaluates to
63 * FALSE, the result will be lowercase.
65 * @param bool $upperCase
66 * (optional) Whether the result is uppercase (true) or lowercase (false).
69 * The generated string.
71 * @see \Drupal\system\Tests\Theme\TwigExtensionTest::testTwigExtensionFunction()
73 public static function testFunction($upperCase = FALSE) {
74 $string = "The quick brown box jumps over the lazy dog 123.";
75 if ($upperCase == TRUE) {
76 return strtoupper($string);
79 return strtolower($string);
84 * Replaces all instances of "animal" in a string with "plant".
86 * @param string $string
87 * The string to be filtered.
90 * The filtered string.
92 * @see \Drupal\system\Tests\Theme\TwigExtensionTest::testTwigExtensionFilter()
94 public static function testFilter($string) {
95 return str_replace(['animal'], ['plant'], $string);