1

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>
5
  • 1
    That seems dangerous. Why not just strip the tags from the sliced part? Feb 22, 2023 at 11:09
  • |raw is to be avoided.
    – mona lisa
    Feb 22, 2023 at 12:04
  • @Patrick Kenny because the code html is displayed
    – Matoeil
    Feb 22, 2023 at 13:09
  • @cileven could u please develop why ? drupal.stackexchange.com/questions/299321/…
    – Matoeil
    Feb 22, 2023 at 14:22
  • It is absolutely dangerous to use |raw because it does not filter output. That ^ question is about whether |raw was deprecated.
    – mona lisa
    Feb 22, 2023 at 16:57

1 Answer 1

5

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.

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.