3 namespace Drupal\Core\Template;
5 use Drupal\Component\Utility\Html;
6 use Drupal\Component\Render\MarkupInterface;
7 use Drupal\Core\Cache\CacheableDependencyInterface;
8 use Drupal\Core\Datetime\DateFormatterInterface;
9 use Drupal\Core\Render\AttachmentsInterface;
10 use Drupal\Core\Render\BubbleableMetadata;
11 use Drupal\Core\Render\Markup;
12 use Drupal\Core\Render\RenderableInterface;
13 use Drupal\Core\Render\RendererInterface;
14 use Drupal\Core\Routing\UrlGeneratorInterface;
15 use Drupal\Core\Theme\ThemeManagerInterface;
19 * A class providing Drupal Twig extensions.
21 * This provides a Twig extension that registers various Drupal-specific
22 * extensions to Twig, specifically Twig functions, filter, and node visitors.
24 * @see \Drupal\Core\CoreServiceProvider
26 class TwigExtension extends \Twig_Extension {
31 * @var \Drupal\Core\Routing\UrlGeneratorInterface
33 protected $urlGenerator;
38 * @var \Drupal\Core\Render\RendererInterface
45 * @var \Drupal\Core\Theme\ThemeManagerInterface
47 protected $themeManager;
52 * @var \Drupal\Core\Datetime\DateFormatterInterface
54 protected $dateFormatter;
57 * Constructs \Drupal\Core\Template\TwigExtension.
59 * @param \Drupal\Core\Render\RendererInterface $renderer
61 * @param \Drupal\Core\Routing\UrlGeneratorInterface $url_generator
63 * @param \Drupal\Core\Theme\ThemeManagerInterface $theme_manager
65 * @param \Drupal\Core\Datetime\DateFormatterInterface $date_formatter
68 public function __construct(RendererInterface $renderer, UrlGeneratorInterface $url_generator, ThemeManagerInterface $theme_manager, DateFormatterInterface $date_formatter) {
69 $this->renderer = $renderer;
70 $this->urlGenerator = $url_generator;
71 $this->themeManager = $theme_manager;
72 $this->dateFormatter = $date_formatter;
76 * Sets the URL generator.
78 * @param \Drupal\Core\Routing\UrlGeneratorInterface $url_generator
83 * @deprecated in Drupal 8.0.x-dev, will be removed before Drupal 9.0.0.
85 public function setGenerators(UrlGeneratorInterface $url_generator) {
86 return $this->setUrlGenerator($url_generator);
90 * Sets the URL generator.
92 * @param \Drupal\Core\Routing\UrlGeneratorInterface $url_generator
97 * @deprecated in Drupal 8.3.x-dev, will be removed before Drupal 9.0.0.
99 public function setUrlGenerator(UrlGeneratorInterface $url_generator) {
100 $this->urlGenerator = $url_generator;
105 * Sets the theme manager.
107 * @param \Drupal\Core\Theme\ThemeManagerInterface $theme_manager
112 * @deprecated in Drupal 8.3.x-dev, will be removed before Drupal 9.0.0.
114 public function setThemeManager(ThemeManagerInterface $theme_manager) {
115 $this->themeManager = $theme_manager;
120 * Sets the date formatter.
122 * @param \Drupal\Core\Datetime\DateFormatter $date_formatter
123 * The date formatter.
127 * @deprecated in Drupal 8.3.x-dev, will be removed before Drupal 9.0.0.
129 public function setDateFormatter(DateFormatterInterface $date_formatter) {
130 $this->dateFormatter = $date_formatter;
137 public function getFunctions() {
139 // This function will receive a renderable array, if an array is detected.
140 new \Twig_SimpleFunction('render_var', [$this, 'renderVar']),
141 // The url and path function are defined in close parallel to those found
142 // in \Symfony\Bridge\Twig\Extension\RoutingExtension
143 new \Twig_SimpleFunction('url', [$this, 'getUrl'], ['is_safe_callback' => [$this, 'isUrlGenerationSafe']]),
144 new \Twig_SimpleFunction('path', [$this, 'getPath'], ['is_safe_callback' => [$this, 'isUrlGenerationSafe']]),
145 new \Twig_SimpleFunction('link', [$this, 'getLink']),
146 new \Twig_SimpleFunction('file_url', function ($uri) {
147 return file_url_transform_relative(file_create_url($uri));
149 new \Twig_SimpleFunction('attach_library', [$this, 'attachLibrary']),
150 new \Twig_SimpleFunction('active_theme_path', [$this, 'getActiveThemePath']),
151 new \Twig_SimpleFunction('active_theme', [$this, 'getActiveTheme']),
152 new \Twig_SimpleFunction('create_attribute', [$this, 'createAttribute']),
159 public function getFilters() {
161 // Translation filters.
162 new \Twig_SimpleFilter('t', 't', ['is_safe' => ['html']]),
163 new \Twig_SimpleFilter('trans', 't', ['is_safe' => ['html']]),
164 // The "raw" filter is not detectable when parsing "trans" tags. To detect
165 // which prefix must be used for translation (@, !, %), we must clone the
166 // "raw" filter and give it identifiable names. These filters should only
167 // be used in "trans" tags.
168 // @see TwigNodeTrans::compileString()
169 new \Twig_SimpleFilter('placeholder', [$this, 'escapePlaceholder'], ['is_safe' => ['html'], 'needs_environment' => TRUE]),
171 // Replace twig's escape filter with our own.
172 new \Twig_SimpleFilter('drupal_escape', [$this, 'escapeFilter'], ['needs_environment' => TRUE, 'is_safe_callback' => 'twig_escape_filter_is_safe']),
174 // Implements safe joining.
175 // @todo Make that the default for |join? Upstream issue:
176 // https://github.com/fabpot/Twig/issues/1420
177 new \Twig_SimpleFilter('safe_join', [$this, 'safeJoin'], ['needs_environment' => TRUE, 'is_safe' => ['html']]),
180 new \Twig_SimpleFilter('without', 'twig_without'),
182 // CSS class and ID filters.
183 new \Twig_SimpleFilter('clean_class', '\Drupal\Component\Utility\Html::getClass'),
184 new \Twig_SimpleFilter('clean_id', '\Drupal\Component\Utility\Html::getId'),
185 // This filter will render a renderable array to use the string results.
186 new \Twig_SimpleFilter('render', [$this, 'renderVar']),
187 new \Twig_SimpleFilter('format_date', [$this->dateFormatter, 'format']),
194 public function getNodeVisitors() {
195 // The node visitor is needed to wrap all variables with
196 // render_var -> TwigExtension->renderVar() function.
198 new TwigNodeVisitor(),
205 public function getTokenParsers() {
207 new TwigTransTokenParser(),
214 public function getName() {
215 return 'drupal_core';
219 * Generates a URL path given a route name and parameters.
222 * The name of the route.
223 * @param array $parameters
224 * An associative array of route parameters names and values.
225 * @param array $options
226 * (optional) An associative array of additional options. The 'absolute'
227 * option is forced to be FALSE.
230 * The generated URL path (relative URL) for the given route.
232 * @see \Drupal\Core\Routing\UrlGeneratorInterface::generateFromRoute()
234 public function getPath($name, $parameters = [], $options = []) {
235 $options['absolute'] = FALSE;
236 return $this->urlGenerator->generateFromRoute($name, $parameters, $options);
240 * Generates an absolute URL given a route name and parameters.
243 * The name of the route.
244 * @param array $parameters
245 * An associative array of route parameter names and values.
246 * @param array $options
247 * (optional) An associative array of additional options. The 'absolute'
248 * option is forced to be TRUE.
251 * The generated absolute URL for the given route.
253 * @todo Add an option for scheme-relative URLs.
255 public function getUrl($name, $parameters = [], $options = []) {
257 $options['absolute'] = TRUE;
258 $generated_url = $this->urlGenerator->generateFromRoute($name, $parameters, $options, TRUE);
260 // Return as render array, so we can bubble the bubbleable metadata.
261 $build = ['#markup' => $generated_url->getGeneratedUrl()];
262 $generated_url->applyTo($build);
267 * Gets a rendered link from a url object.
269 * @param string $text
270 * The link text for the anchor tag as a translated string.
271 * @param \Drupal\Core\Url|string $url
272 * The URL object or string used for the link.
273 * @param array|\Drupal\Core\Template\Attribute $attributes
274 * An optional array or Attribute object of link attributes.
277 * A render array representing a link to the given URL.
279 public function getLink($text, $url, $attributes = []) {
280 if (!$url instanceof Url) {
281 $url = Url::fromUri($url);
283 // The twig extension should not modify the original URL object, this
284 // ensures consistent rendering.
285 // @see https://www.drupal.org/node/2842399
288 if ($attributes instanceof Attribute) {
289 $attributes = $attributes->toArray();
291 $url->mergeOptions(['attributes' => $attributes]);
293 // The text has been processed by twig already, convert it to a safe object
294 // for the render system.
295 if ($text instanceof \Twig_Markup) {
296 $text = Markup::create($text);
307 * Gets the name of the active theme.
310 * The name of the active theme.
312 public function getActiveTheme() {
313 return $this->themeManager->getActiveTheme()->getName();
317 * Gets the path of the active theme.
320 * The path to the active theme.
322 public function getActiveThemePath() {
323 return $this->themeManager->getActiveTheme()->getPath();
327 * Determines at compile time whether the generated URL will be safe.
329 * Saves the unneeded automatic escaping for performance reasons.
331 * The URL generation process percent encodes non-alphanumeric characters.
332 * Thus, the only character within a URL that must be escaped in HTML is the
333 * ampersand ("&") which separates query params. Thus we cannot mark
334 * the generated URL as always safe, but only when we are sure there won't be
335 * multiple query params. This is the case when there are none or only one
336 * constant parameter given. For instance, we know beforehand this will not
337 * need to be escaped:
339 * - path('route', {'param': 'value'})
340 * But the following may need to be escaped:
341 * - path('route', var)
342 * - path('route', {'param': ['val1', 'val2'] }) // a sub-array
343 * - path('route', {'param1': 'value1', 'param2': 'value2'})
344 * If param1 and param2 reference placeholders in the route, it would not
345 * need to be escaped, but we don't know that in advance.
347 * @param \Twig_Node $args_node
348 * The arguments of the path/url functions.
351 * An array with the contexts the URL is safe
353 public function isUrlGenerationSafe(\Twig_Node $args_node) {
354 // Support named arguments.
355 $parameter_node = $args_node->hasNode('parameters') ? $args_node->getNode('parameters') : ($args_node->hasNode(1) ? $args_node->getNode(1) : NULL);
357 if (!isset($parameter_node) || $parameter_node instanceof \Twig_Node_Expression_Array && count($parameter_node) <= 2 &&
358 (!$parameter_node->hasNode(1) || $parameter_node->getNode(1) instanceof \Twig_Node_Expression_Constant)) {
366 * Attaches an asset library to the template, and hence to the response.
368 * Allows Twig templates to attach asset libraries using
370 * {{ attach_library('extension/library_name') }}
373 * @param string $library
376 public function attachLibrary($library) {
377 // Use Renderer::render() on a temporary render array to get additional
378 // bubbleable metadata on the render stack.
379 $template_attached = ['#attached' => ['library' => [$library]]];
380 $this->renderer->render($template_attached);
384 * Provides a placeholder wrapper around ::escapeFilter.
386 * @param \Twig_Environment $env
387 * A Twig_Environment instance.
388 * @param mixed $string
389 * The value to be escaped.
391 * @return string|null
392 * The escaped, rendered output, or NULL if there is no valid output.
394 public function escapePlaceholder($env, $string) {
395 return '<em class="placeholder">' . $this->escapeFilter($env, $string) . '</em>';
399 * Overrides twig_escape_filter().
401 * Replacement function for Twig's escape filter.
403 * Note: This function should be kept in sync with
404 * theme_render_and_autoescape().
406 * @param \Twig_Environment $env
407 * A Twig_Environment instance.
409 * The value to be escaped.
410 * @param string $strategy
411 * The escaping strategy. Defaults to 'html'.
412 * @param string $charset
414 * @param bool $autoescape
415 * Whether the function is called by the auto-escaping feature (TRUE) or by
416 * the developer (FALSE).
418 * @return string|null
419 * The escaped, rendered output, or NULL if there is no valid output.
422 * When $arg is passed as an object which does not implement __toString(),
423 * RenderableInterface or toString().
425 * @todo Refactor this to keep it in sync with theme_render_and_autoescape()
426 * in https://www.drupal.org/node/2575065
428 public function escapeFilter(\Twig_Environment $env, $arg, $strategy = 'html', $charset = NULL, $autoescape = FALSE) {
429 // Check for a numeric zero int or float.
430 if ($arg === 0 || $arg === 0.0) {
434 // Return early for NULL and empty arrays.
439 $this->bubbleArgMetadata($arg);
441 // Keep Twig_Markup objects intact to support autoescaping.
442 if ($autoescape && ($arg instanceof \Twig_Markup || $arg instanceof MarkupInterface)) {
448 if (is_scalar($arg)) {
449 $return = (string) $arg;
451 elseif (is_object($arg)) {
452 if ($arg instanceof RenderableInterface) {
453 $arg = $arg->toRenderable();
455 elseif (method_exists($arg, '__toString')) {
456 $return = (string) $arg;
458 // You can't throw exceptions in the magic PHP __toString() methods, see
459 // http://php.net/manual/language.oop5.magic.php#object.tostring so
460 // we also support a toString method.
461 elseif (method_exists($arg, 'toString')) {
462 $return = $arg->toString();
465 throw new \Exception('Object of type ' . get_class($arg) . ' cannot be printed.');
469 // We have a string or an object converted to a string: Autoescape it!
470 if (isset($return)) {
471 if ($autoescape && $return instanceof MarkupInterface) {
474 // Drupal only supports the HTML escaping strategy, so provide a
475 // fallback for other strategies.
476 if ($strategy == 'html') {
477 return Html::escape($return);
479 return twig_escape_filter($env, $return, $strategy, $charset, $autoescape);
482 // This is a normal render array, which is safe by definition, with
483 // special simple cases already handled.
485 // Early return if this element was pre-rendered (no need to re-render).
486 if (isset($arg['#printed']) && $arg['#printed'] == TRUE && isset($arg['#markup']) && strlen($arg['#markup']) > 0) {
487 return $arg['#markup'];
489 $arg['#printed'] = FALSE;
490 return $this->renderer->render($arg);
494 * Bubbles Twig template argument's cacheability & attachment metadata.
496 * For example: a generated link or generated URL object is passed as a Twig
497 * template argument, and its bubbleable metadata must be bubbled.
499 * @see \Drupal\Core\GeneratedLink
500 * @see \Drupal\Core\GeneratedUrl
503 * A Twig template argument that is about to be printed.
505 * @see \Drupal\Core\Theme\ThemeManager::render()
506 * @see \Drupal\Core\Render\RendererInterface::render()
508 protected function bubbleArgMetadata($arg) {
509 // If it's a renderable, then it'll be up to the generated render array it
510 // returns to contain the necessary cacheability & attachment metadata. If
511 // it doesn't implement CacheableDependencyInterface or AttachmentsInterface
512 // then there is nothing to do here.
513 if ($arg instanceof RenderableInterface || !($arg instanceof CacheableDependencyInterface || $arg instanceof AttachmentsInterface)) {
517 $arg_bubbleable = [];
518 BubbleableMetadata::createFromObject($arg)
519 ->applyTo($arg_bubbleable);
521 $this->renderer->render($arg_bubbleable);
525 * Wrapper around render() for twig printed output.
527 * If an object is passed which does not implement __toString(),
528 * RenderableInterface or toString() then an exception is thrown;
529 * Other objects are casted to string. However in the case that the
530 * object is an instance of a Twig_Markup object it is returned directly
531 * to support auto escaping.
533 * If an array is passed it is rendered via render() and scalar values are
537 * String, Object or Render Array.
540 * When $arg is passed as an object which does not implement __toString(),
541 * RenderableInterface or toString().
544 * The rendered output or an Twig_Markup object.
547 * @see TwigNodeVisitor
549 public function renderVar($arg) {
550 // Check for a numeric zero int or float.
551 if ($arg === 0 || $arg === 0.0) {
555 // Return early for NULL and empty arrays.
560 // Optimize for scalars as it is likely they come from the escape filter.
561 if (is_scalar($arg)) {
565 if (is_object($arg)) {
566 $this->bubbleArgMetadata($arg);
567 if ($arg instanceof RenderableInterface) {
568 $arg = $arg->toRenderable();
570 elseif (method_exists($arg, '__toString')) {
571 return (string) $arg;
573 // You can't throw exceptions in the magic PHP __toString() methods, see
574 // http://php.net/manual/language.oop5.magic.php#object.tostring so
575 // we also support a toString method.
576 elseif (method_exists($arg, 'toString')) {
577 return $arg->toString();
580 throw new \Exception('Object of type ' . get_class($arg) . ' cannot be printed.');
584 // This is a render array, with special simple cases already handled.
585 // Early return if this element was pre-rendered (no need to re-render).
586 if (isset($arg['#printed']) && $arg['#printed'] == TRUE && isset($arg['#markup']) && strlen($arg['#markup']) > 0) {
587 return $arg['#markup'];
589 $arg['#printed'] = FALSE;
590 return $this->renderer->render($arg);
594 * Joins several strings together safely.
596 * @param \Twig_Environment $env
597 * A Twig_Environment instance.
598 * @param mixed[]|\Traversable|null $value
599 * The pieces to join.
600 * @param string $glue
601 * The delimiter with which to join the string. Defaults to an empty string.
602 * This value is expected to be safe for output and user provided data
603 * should never be used as a glue.
606 * The strings joined together.
608 public function safeJoin(\Twig_Environment $env, $value, $glue = '') {
609 if ($value instanceof \Traversable) {
610 $value = iterator_to_array($value, FALSE);
613 return implode($glue, array_map(function ($item) use ($env) {
614 // If $item is not marked safe then it will be escaped.
615 return $this->escapeFilter($env, $item, 'html', NULL, TRUE);
620 * Creates an Attribute object.
622 * @param array $attributes
623 * (optional) An associative array of key-value pairs to be converted to
626 * @return \Drupal\Core\Template\Attribute
627 * An attributes object that has the given attributes.
629 public function createAttribute(array $attributes = []) {
630 return new Attribute($attributes);