0

We have a mytheme.theme file that has a mytheme_preprocess_node(&$variables) function. Within this preprocess hook, we would like to remove all HTML tags within a formatted (long) field. The goal is to do without using striptags within the node--page.html.twig template.

How can we do this securely without using striptags in a twig template?

Here is what we tried, but cannot find how to do it using mytheme_preprocess_node hook.

mytheme.theme

function mytheme_preprocess_node(&$variables) {

  $node = $variables['node'];
  $field_value = $node->get('body')->first()->getValue()['value'];
  ksm($field_value);
  // cannot find way to remove `html` tags

  $variables['field_value'] = $field_value;
}

node--page.html.twig

{{ field_value }}

output of ksm($field_value)

"& lt;p & gt;When looking at & lt;a href="https://www.example.com/some-path/"& gt;article trends& lt;/a& gt; over time, attacks are cyclical in nature. Attackers develop new attack types and vectors, which are used to launch a new wave of attacks. As defenders become more proficient in stopping these new attacks, the attackers develop new types of attacks and the cycle repeats itself.</p& gt;

In order to properly display the output, I had to a space between & and lt characters above because StackExchange will convert those to proper tags. Within the ksm statement there is no space.

Additional item we tried within a twig template, but not sure if it is secure.

{% set body_processed = {
  '#type' : 'processed_text',
  '#text' : content.body.0,
  '#format' : content.body.format
} %}
4
  • You could use strip_tags() in PHP like in Twig, there is no difference, but this is not safe. You need to process the text format with the text filters now configured for the input data and add an additional one for removing the tags.
    – 4uk4
    Commented May 24, 2019 at 7:00
  • @4k4 only other option is to do {{ field_value|render|striptags }} in the twig templates, but i found that striptags is also not safe Commented May 24, 2019 at 16:34
  • Is there a reason why you don't want to output the field rendered normally in a safe way?
    – 4uk4
    Commented May 24, 2019 at 16:58
  • @4k4 Yes because we want to use the output in snippets such as ones in the question here Commented May 24, 2019 at 17:15

1 Answer 1

1

Then better apply strip_tags() on the processed text $node->body->processed. You might also want to apply Html::decodeEntities(). Still take care you configure the text format restrictively, because outputting the text in a non standard way can be a security risk increasing with features you allow. And you don't get security updates for custom code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.