diff --git a/src/TwigExtension.php b/src/TwigExtension.php index f5571ac..4c3e14e 100644 --- a/src/TwigExtension.php +++ b/src/TwigExtension.php @@ -95,6 +95,9 @@ class TwigExtension extends \Twig_Extension { new \Twig_SimpleFunction('drupal_field', [$this, 'drupalField']), new \Twig_SimpleFunction('drupal_menu', [$this, 'drupalMenu']), new \Twig_SimpleFunction('drupal_config', [$this, 'drupalConfig']), + // Wrap drupal_set_message() because it returns some value which is not + // suitable for Twig template. + new \Twig_SimpleFunction('drupal_set_message', [$this, 'drupalSetMessage']), ]; } @@ -333,4 +336,21 @@ class TwigExtension extends \Twig_Extension { return file_url_transform_relative($url); } + /** + * Sets a message to display to the user. + * + * @param string|\Drupal\Component\Render\MarkupInterface $message + * (optional) The translated message to be displayed to the user. + * @param string $type + * (optional) The message's type. Defaults to 'status'. + * @param bool $repeat + * (optional) If this is FALSE and the message is already set, then the + * message won't be repeated. Defaults to FALSE. + * + * @see drupal_set_message() + */ + public function drupalSetMessage($message = NULL, $type = 'status', $repeat = FALSE) { + drupal_set_message($message, $type, $repeat); + } + } diff --git a/tests/src/Functional/TwigTweakTest.php b/tests/src/Functional/TwigTweakTest.php index e277f4f..c0acbb7 100644 --- a/tests/src/Functional/TwigTweakTest.php +++ b/tests/src/Functional/TwigTweakTest.php @@ -117,6 +117,10 @@ class TwigTweakTest extends BrowserTestBase { $xpath = '//div[@class = "tt-config" and . = "Anonymous"]'; $this->assertByXpath($xpath); + // Test status message. + $xpath = '//div[@class = "messages messages--warning" and contains(., "Hi!")]'; + $this->assertByXpath($xpath); + // Test token replacement. $xpath = '//div[@class = "tt-token-replace" and . = "Site name: Drupal"]'; $this->assertByXpath($xpath); diff --git a/tests/twig_tweak_test/templates/twig-tweak-test.html.twig b/tests/twig_tweak_test/templates/twig-tweak-test.html.twig index bf4d882..1b6cc46 100644 --- a/tests/twig_tweak_test/templates/twig-tweak-test.html.twig +++ b/tests/twig_tweak_test/templates/twig-tweak-test.html.twig @@ -13,6 +13,7 @@
{{ drupal_token('site:name') }}
{{ drupal_token('node:title', {'node': node}) }}
{{ drupal_config('user.settings', 'anonymous') }}
+
{{ drupal_set_message('Hi!', 'warning') }}
{{ 'Site name: [site:name]' | token_replace }}
{{ 'foo' | preg_replace('(foo)', '$1-bar') }}
{{ 'public://images/ocean.jpg' | image_style('thumbnail') }}