0

I don't know if that stupid question has already been asked...

But how should I output a field type "text_long" in Twig ?

Now what I do is to set myself an array with that :

$data = $journalist->field_bio->getValue();

$user['bio'] = [
                    '#type' => 'processed_text',
                    '#text' => $data[0]['value'],
                    '#format' => 'full_html'
               ];

Because I cannot find the filter to render a text_long in html.

In the twig I tried : {{ user.bio | raw }}, {{ user.bio | render }}...

=> What's the drupal 8 way to handle that ?

2

The Drupal 8 way would be to use a view mode and let the field formatter do its work.

If you want to do this in custom code you can build the render element for processed text like you did in the question, but use the text format stored in the field:

$user['bio'] = [
  '#type' => 'processed_text',
  '#text' => $data[0]['value'],
  '#format' => $data[0]['format'],
];

Then you are sure, that the text filters are applied configured in the format, that the user who filled in the text field had permission to use.

To output the variable in twig you don't need any filters, they are applied automatically by the render element:

{{ user.bio }}

Edit for the question in the comment, how to render a field without a view mode. There is a way to do this. You can view a field by providing the display options in an array:

$user['bio'] = $journalist->field_bio->view(['label' => 'hidden', 'type' => 'text_default']);

But this is as expensive as rendering the complete entity and is not optimized for caching. So use it only if you can't figure out a way how to render whole entities in view modes.

  • So there is no better way to handle that or at least a small helper ? Unfortunately for my case, I cannot use a view mode because it's for a very custom page – injetkilo May 3 '17 at 15:09
  • You can use the view() method of the field, see the edit. – 4k4 May 3 '17 at 16:44

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.