Score:1

is there a twig filter to correct the HTML?

za flag

the slice filter on html code can generate invalid html that can cause in cascade JS errors

 {% set text = paragraph.field_verbatim_text.value %}
 {% if text|striptags|length > 300 %}
    {{ text|slice(0, 310)|raw }} [&hellip;]<a class="verbatim__suite" aria-label="{{ 'Read the full text'|t }}"
                                                       href="#verbatim-{{ paragraph.id() }}"
                                                       data-open="verbatim-{{ paragraph.id() }}">{{ 'Read more'|t }}</a>
cn flag
That seems dangerous. Why not just strip the tags from the sliced part?
id flag
`|raw` is to be avoided.
Matoeil avatar
za flag
@Patrick Kenny because the code html is displayed
Matoeil avatar
za flag
@cileven could u please develop why ? https://drupal.stackexchange.com/questions/299321/what-should-be-used-instead-of-raw-filter
id flag
It is absolutely dangerous to use `|raw` because it does not filter output. That ^ question is about whether `|raw` was deprecated.
Score:5
cn flag

Instead of the insecure |raw filter use the render element processed_text. This applies the filters of the text format and marks the filtered result as safe so that you don't need the |raw filter anymore:

{% set text_sliced = {
  '#type':   'processed_text',
  '#text':    paragraph.field_verbatim_text.value|slice(0, 310),
  '#format':  'basic_html',
} %}

{{ text_sliced }}

Most text formats should correct the HTML out of the box. If the text format the field uses now doesn't work, configure a custom text format for this purpose and enable the "Correct faulty and chopped off HTML" filter.


Never output user input unfiltered

The link in the comment is about the raw filter not being deprecated, a false alarm when you are confusing it with the verbatim tag. Nonetheless, the security issue is about bypassing the autoescape mechanism, in Drupal enabled by default for any template. One way is the raw filter, but there are many others, in Twig and PHP. Only do this if you are sure it's safe. User input should never be considered as safe.

I sit in a Tesla and translated this thread with Ai:

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.