1

What is the alternative to the |raw filter if I want to output html from a entity field in twig in Drupal 8?

According to this ticket, |raw should be avoided, but I can't figure out how to use what they recommend in that ticket (Safestring/SafeMarkup) in twig.

I have a custom content entity that has a field definition as follows:

$fields['internal_description'] = BaseFieldDefinition::create('text_long')
  ->setLabel(t('Internal description'))
  ->setSettings(array(
    'max_length' => 1500,
  ))

The field stores HTML from a CKEditor instance. Now I would like to output this as HTML in a twig template. Currently if I just call

{{  event.getExternalDescription }}

I get the escaped HTML as expected, however that is not what I want. If I do

{{  event.getExternalDescription | raw }}

I get what I want, which is unescaped, rendered HTML. However since it's not checked in any way in this case, I would like to know how to make this output safe and still allow my users to use CKEditor for entering content?

  • What they do in that ticket is use a preprocess hook to add Markup render elements as twig variables. That way, there is no need for the raw filter. That way, you can use the added twig variables directly in your twig template. – Stefanos Petrakis Dec 27 '16 at 13:03
2

Normally you would configure the text format to output the field in ui.

You can do this in code by using the render element processed_text.

PHP

  $build = [
    '#type' => 'processed_text',
    '#text' => '<p>Hello world</p>',
    '#format' => 'full_html',
  ];

TWIG

In twig you would use instead of the extremely unsafe {{ event.getExternalDescription | raw }} this code:

  {% set build = {
    '#type':   'processed_text',
    '#text':    event.getExternalDescription,
    '#format': 'full_html',
  } %}

  {{ build }}

The safety of the text format depends on the configuration of the text filters and the content of the field. You still have to apply the same security consideraton as when using this text format in ckeditor.

0

This type of usage worked for me, in making a long text wysiwyg field render that was within a paragraph entity on a node:

{{ item.entity.field_innerfieldname.value|t() }}

Specifically within nodes where field_paragraph_items is the set of paragraph elements:

{% for item in content['#node'].field_paragraph_items %}

It took a while to figure this out. the twig processor |t() is not widely advertised.

See also:

  • I don't think you can translate field content like this, t() is for string constants and for security reasons variables are only allowed in placeholders. – 4k4 Jun 19 '18 at 10:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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