/Drupal 8

public function TwigExtension::isUrlGenerationSafe

public TwigExtension::isUrlGenerationSafe(\Twig_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.


\Twig_Node $args_node: The arguments of the path/url functions.

Return value

array An array with the contexts the URL is safe


core/lib/Drupal/Core/Template/TwigExtension.php, line 331


A class providing Drupal Twig extensions.




public function isUrlGenerationSafe(\Twig_Node $args_node) {
  // Support named arguments.
  $parameter_node = $args_node->hasNode('parameters') ? $args_node->getNode('parameters') : ($args_node->hasNode(1) ? $args_node->getNode(1) : NULL);

  if (!isset($parameter_node) || $parameter_node instanceof \Twig_Node_Expression_Array && count($parameter_node) <= 2 && 
    (!$parameter_node->hasNode(1) || $parameter_node->getNode(1) instanceof \Twig_Node_Expression_Constant)) {
    return array('html');

  return array();

© 2001–2016 by the original authors
Licensed under the GNU General Public License, version 2 and later.
Drupal is a registered trademark of Dries Buytaert.