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
} %}
{{ field_value|render|striptags }}
in thetwig
templates, but i found thatstriptags
is also not safe