Double escaping

Since Twig already does much of the work for us, it's also important not to go overboard with escaping. Veteran Drupal 7 developers may have a tendency to escape things like there is no tomorrow, but this can have unintended consequences. For example, imagine the following scenario:

return [
  '#theme' => 'my_custom_theme',
  '#title' => 'The cow\'s got milk.',
];

Since Twig is auto-escaping, the following string will be printed:

The cow's got milk.

So, there is no visible change as the string was safe. However, imagine that we were overzealous with our sanitization and did this:

return [
  '#theme' => 'my_custom_theme',
  '#title' => Html::escape('The cow\'s got milk.'),
];

Then, we would get the following title:

The cow's got milk. ...

Get Drupal 8 Module Development now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.