3 namespace Drupal\twig_extension_test\TwigExtension;
7 * A test Twig extension that adds a custom function and a custom filter.
9 class TestExtension extends \Twig_Extension {
12 * Generates a list of all Twig functions that this extension defines.
15 * A key/value array that defines custom Twig functions. The key denotes the
16 * function name used in the tag, e.g.:
21 * The value is a standard PHP callback that defines what the function does.
23 public function getFunctions() {
25 'testfunc' => new \Twig_Function_Function(['Drupal\twig_extension_test\TwigExtension\TestExtension', 'testFunction']),
30 * Generates a list of all Twig filters that this extension defines.
33 * A key/value array that defines custom Twig filters. The key denotes the
34 * filter name used in the tag, e.g.:
36 * {{ foo|testfilter }}
39 * The value is a standard PHP callback that defines what the filter does.
41 public function getFilters() {
43 'testfilter' => new \Twig_Filter_Function(['Drupal\twig_extension_test\TwigExtension\TestExtension', 'testFilter']),
48 * Gets a unique identifier for this Twig extension.
51 * A unique identifier for this Twig extension.
53 public function getName() {
54 return 'twig_extension_test.test_extension';
58 * Outputs either an uppercase or lowercase test phrase.
60 * The function generates either an uppercase or lowercase version of the
61 * phrase "The quick brown fox jumps over the lazy dog 123.", depending on
62 * whether or not the $upperCase parameter evaluates to TRUE. If $upperCase
63 * evaluates to TRUE, the result will be uppercase, and if it evaluates to
64 * FALSE, the result will be lowercase.
66 * @param bool $upperCase
67 * (optional) Whether the result is uppercase (true) or lowercase (false).
70 * The generated string.
72 * @see \Drupal\system\Tests\Theme\TwigExtensionTest::testTwigExtensionFunction()
74 public static function testFunction($upperCase = FALSE) {
75 $string = "The quick brown box jumps over the lazy dog 123.";
76 if ($upperCase == TRUE) {
77 return strtoupper($string);
80 return strtolower($string);
85 * Replaces all instances of "animal" in a string with "plant".
87 * @param string $string
88 * The string to be filtered.
91 * The filtered string.
93 * @see \Drupal\system\Tests\Theme\TwigExtensionTest::testTwigExtensionFilter()
95 public static function testFilter($string) {
96 return str_replace(['animal'], ['plant'], $string);