function TwigExtension::isUrlGenerationSafe

Same name in other branches
  1. 9 core/lib/Drupal/Core/Template/TwigExtension.php \Drupal\Core\Template\TwigExtension::isUrlGenerationSafe()
  2. 8.9.x core/lib/Drupal/Core/Template/TwigExtension.php \Drupal\Core\Template\TwigExtension::isUrlGenerationSafe()
  3. 10 core/lib/Drupal/Core/Template/TwigExtension.php \Drupal\Core\Template\TwigExtension::isUrlGenerationSafe()

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

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

Return value

array An array with the contexts the URL is safe

File

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

Class

TwigExtension
A class providing Drupal Twig extensions.

Namespace

Drupal\Core\Template

Code

public function isUrlGenerationSafe(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 ArrayExpression && count($parameter_node) <= 2 && (!$parameter_node->hasNode(1) || $parameter_node->getNode(1) instanceof ConstantExpression)) {
        return [
            'html',
        ];
    }
    return [];
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.