Drupal - How can I render plain text as HTML in a template?

A solution by iworkyon from the Drupal community:

field--node--[field name].html.twig:

{% if svg %}
  <div class="my-svg">
    {{ svg|raw }}
  </div>
{% endif %}

MYTHEME.theme:

/**
* Implements hook_preprocess_field().
*/
function MYTHEME_preprocess_field(&$variables, $hook) {
    switch ($variables['element']['#field_name']) {
      case 'field_svg_test':
        $variables['svg'] = $variables['items'][0]['content']['#context']['value'];
        break;
    }
}

This worked for me:

{{ item.content['#context'].value|raw }}

Did you try to apply the raw filter on the value?

{{ item.content.context.value|raw }}

But this is not secure. To output files, you can use a file field. This has the correct field formatters to generate the link. If you are not able to configure the link in the ui to your needs, you can modify the twig or preprocess for this specific field.

Tags:

Theming

8