Thumbnail

How to fix usage of {{value|raw}}

Thumbnail

Si Hobbs

|

You found a |raw in a Drupal twig file? Here's a quick fix, and why it's important.

Thanks to Lee Rowlands for help with this, it's been nagging me for a while as I've not had a clean answer for this problem.

Quick answer

If you see {{ foobar|raw }} in twig, trace this back to the template preprocessing, you may find that:

// Will be escaped in twig.
$variables['foobar'] = $node->field_something->value;

Which you can replace with the following and remove the |raw.

// Will be processed correctly in twig.
$variables['foobar'] = $node->field_something->processed;

What is XSS?

You can google what XSS is, but in a nutshell for this article:

  1. Sending unexpected (evil) javascript to the browser.

  2. The risk of that javascript doing nasty criminal things.

So in a practical sense, even if our content editors are trusted we should not allow anything that can cause security issues. They can paste content which has javascript embedded in it. Plus, we don't know how the site will be used in the future or whether future editors will be trusted.

The problem seems to be ...

Usually the twig variables are set up correctly by Drupal, and you can output a formatted text field with just {{ body }}. This will respect the text format that has been used for that field.

In some cases, new variables have been added or altered, and they have not been set up correctly. A themer might be told that foobar contains some preprocessed data, but using {{ foobar }} results in stripping the HTML tags.

Naturally the themer googles a solution for this, and the quickest solution they find is {{ foobar|raw }}. This works, the task is finished and the code is shipped. But on top of XSS issues, there has also introduced other risks - we strip HTML for good reasons, some HTML tags will break our layout. 

The solution

You need to trace back to the preprocess function that set up the variable in the first place. You may find a use of ->value that can be replaced with ->processed.

 

 

Add new comment

The content of this field is kept private and will not be shown publicly.

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.

Comments

  • Allowed HTML tags: <em> <strong> <cite> <blockquote cite> <ul type> <ol start type> <li> <dl> <dt> <dd> <p>
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.
  • Use [gist:#####] where ##### is your gist number to embed the gist
    You may also include a specific file within a multi-file gist with [gist:####:my_file].

Spread the word