class TwigExtension extends AbstractExtension (View source)

A class providing Drupal Twig extensions.

This provides a Twig extension that registers various Drupal-specific extensions to Twig, specifically Twig functions, filter, and node visitors.

Properties

protected UrlGeneratorInterface $urlGenerator

The URL generator.

protected RendererInterface $renderer

The renderer.

protected ThemeManagerInterface $themeManager

The theme manager.

protected DateFormatterInterface $dateFormatter

The date formatter.

protected FileUrlGeneratorInterface $fileUrlGenerator

The file URL generator.

Methods

__construct(RendererInterface $renderer, UrlGeneratorInterface $url_generator, ThemeManagerInterface $theme_manager, DateFormatterInterface $date_formatter, FileUrlGeneratorInterface $file_url_generator = NULL)

Constructs \Drupal\Core\Template\TwigExtension.

getFunctions()

{@inheritdoc}

getFilters()

{@inheritdoc}

getNodeVisitors()

{@inheritdoc}

getTokenParsers()

{@inheritdoc}

getName()

{@inheritdoc}

string
getPath($name, array $parameters = [], array $options = [])

Generates a URL path given a route name and parameters.

array
getUrl($name, array $parameters = [], array $options = [])

Generates an absolute URL given a route name and parameters.

array
getLink(string $text, Url|string $url, array|Attribute $attributes = [])

Gets a rendered link from a url object.

string
getActiveTheme()

Gets the name of the active theme.

string
getActiveThemePath()

Gets the path of the active theme.

array
isUrlGenerationSafe(Node $args_node)

Determines at compile time whether the generated URL will be safe.

attachLibrary(string $library)

Attaches an asset library to the template, and hence to the response.

string|null
escapePlaceholder(Environment $env, mixed $string)

Provides a placeholder wrapper around ::escapeFilter.

string|null
escapeFilter(Environment $env, mixed $arg, string $strategy = 'html', string $charset = NULL, bool $autoescape = FALSE)

Overrides twig_escape_filter().

bubbleArgMetadata(mixed $arg)

Bubbles Twig template argument's cacheability & attachment metadata.

mixed
renderVar(mixed $arg)

Wrapper around render() for twig printed output.

string
safeJoin(Environment $env, array|Traversable|null $value, string $glue = '')

Joins several strings together safely.

createAttribute(array $attributes = [])

Creates an Attribute object.

array
withoutFilter(array|object $element)

Removes child elements from a copy of the original array.

Details

__construct(RendererInterface $renderer, UrlGeneratorInterface $url_generator, ThemeManagerInterface $theme_manager, DateFormatterInterface $date_formatter, FileUrlGeneratorInterface $file_url_generator = NULL)

Constructs \Drupal\Core\Template\TwigExtension.

Parameters

RendererInterface $renderer

The renderer.

UrlGeneratorInterface $url_generator

The URL generator.

ThemeManagerInterface $theme_manager

The theme manager.

DateFormatterInterface $date_formatter

The date formatter.

FileUrlGeneratorInterface $file_url_generator

The file URL generator.

getFunctions()

{@inheritdoc}

getFilters()

{@inheritdoc}

getNodeVisitors()

{@inheritdoc}

getTokenParsers()

{@inheritdoc}

getName()

{@inheritdoc}

string getPath($name, array $parameters = [], array $options = [])

Generates a URL path given a route name and parameters.

Parameters

$name

The name of the route.

array $parameters

An associative array of route parameters names and values.

array $options

(optional) An associative array of additional options. The 'absolute' option is forced to be FALSE.

Return Value

string

The generated URL path (relative URL) for the given route.

See also

UrlGeneratorInterface::generateFromRoute

array getUrl($name, array $parameters = [], array $options = [])

Generates an absolute URL given a route name and parameters.

Add an option for scheme-relative URLs.

Parameters

$name

The name of the route.

array $parameters

An associative array of route parameter names and values.

array $options

(optional) An associative array of additional options. The 'absolute' option is forced to be TRUE.

Return Value

array

A render array with generated absolute URL for the given route.

Gets a rendered link from a url object.

Parameters

string $text

The link text for the anchor tag as a translated string.

Url|string $url

The URL object or string used for the link.

array|Attribute $attributes

An optional array or Attribute object of link attributes.

Return Value

array

A render array representing a link to the given URL.

string getActiveTheme()

Gets the name of the active theme.

Return Value

string

The name of the active theme.

string getActiveThemePath()

Gets the path of the active theme.

Return Value

string

The path to the active theme.

array isUrlGenerationSafe(Node $args_node)

Determines at compile time whether the generated URL will be safe.

Saves the unneeded automatic escaping for performance reasons.

The URL generation process percent encodes non-alphanumeric characters. Thus, the only character within a URL that must be escaped in HTML is the ampersand ("&") which separates query params. Thus we cannot mark the generated URL as always safe, but only when we are sure there won't be multiple query params. This is the case when there are none or only one constant parameter given. For instance, we know beforehand this will not need to be escaped:

  • path('route')
  • path('route', {'param': 'value'}) But the following may need to be escaped:
  • path('route', var)
  • path('route', {'param': ['val1', 'val2'] }) // a sub-array
  • path('route', {'param1': 'value1', 'param2': 'value2'}) If param1 and param2 reference placeholders in the route, it would not need to be escaped, but we don't know that in advance.

Parameters

Node $args_node

The arguments of the path/url functions.

Return Value

array

An array with the contexts the URL is safe

attachLibrary(string $library)

Attaches an asset library to the template, and hence to the response.

Allows Twig templates to attach asset libraries using

Parameters

string $library

An asset library.

string|null escapePlaceholder(Environment $env, mixed $string)

Provides a placeholder wrapper around ::escapeFilter.

Parameters

Environment $env

A Twig Environment instance.

mixed $string

The value to be escaped.

Return Value

string|null

The escaped, rendered output, or NULL if there is no valid output.

string|null escapeFilter(Environment $env, mixed $arg, string $strategy = 'html', string $charset = NULL, bool $autoescape = FALSE)

Overrides twig_escape_filter().

Replacement function for Twig's escape filter.

Note: This function should be kept in sync with theme_render_and_autoescape().

Refactor this to keep it in sync with theme_render_and_autoescape() in https://www.drupal.org/node/2575065

Parameters

Environment $env

A Twig Environment instance.

mixed $arg

The value to be escaped.

string $strategy

The escaping strategy. Defaults to 'html'.

string $charset

The charset.

bool $autoescape

Whether the function is called by the auto-escaping feature (TRUE) or by the developer (FALSE).

Return Value

string|null

The escaped, rendered output, or NULL if there is no valid output.

Exceptions

Exception

protected bubbleArgMetadata(mixed $arg)

Bubbles Twig template argument's cacheability & attachment metadata.

For example: a generated link or generated URL object is passed as a Twig template argument, and its bubbleable metadata must be bubbled.

Parameters

mixed $arg

A Twig template argument that is about to be printed.

See also

GeneratedLink
GeneratedUrl
ThemeManager::render
RendererInterface::render

mixed renderVar(mixed $arg)

Wrapper around render() for twig printed output.

If an object is passed which does not implement __toString(), RenderableInterface or toString() then an exception is thrown; Other objects are casted to string. However in the case that the object is an instance of a \Twig\Markup object it is returned directly to support auto escaping.

If an array is passed it is rendered via render() and scalar values are returned directly.

Parameters

mixed $arg

String, Object or Render Array.

Return Value

mixed

The rendered output or a \Twig\Markup object.

Exceptions

Exception

See also

render
TwigNodeVisitor

string safeJoin(Environment $env, array|Traversable|null $value, string $glue = '')

Joins several strings together safely.

Parameters

Environment $env

A Twig Environment instance.

array|Traversable|null $value

The pieces to join.

string $glue

The delimiter with which to join the string. Defaults to an empty string. This value is expected to be safe for output and user provided data should never be used as a glue.

Return Value

string

The strings joined together.

Attribute createAttribute(array $attributes = [])

Creates an Attribute object.

Parameters

array $attributes

(optional) An associative array of key-value pairs to be converted to HTML attributes.

Return Value

Attribute

An attributes object that has the given attributes.

array withoutFilter(array|object $element)

Removes child elements from a copy of the original array.

Creates a copy of the renderable array and removes child elements by key specified through filter's arguments. The copy can be printed without these elements. The original renderable array is still available and can be used to print child elements in their entirety in the twig template.

Parameters

array|object $element

The parent renderable array to exclude the child items.

Return Value

array

The filtered renderable array.