2

I need to render a text (formatted long) field using twig. At this time i am doing the following below. However, i am finding that if i were to add a line break in the text field or apply adding spacing or a horizontal line, the twig filter "raw" removes those attributes. I need assistance to see what I am missing.

I have already set the view mode for field on the content type to default

Twig template (filter used)

{% for item in items %}
    {{ item.field_body.value|raw }}
{% endfor %}

Expecting enter image description here

Actual result enter image description here

5
  • You’re using an HTML enabled filter but then using raw. It won’t print. Why do you need full html if you’re going to remove it?
    – Kevin
    Commented Oct 6, 2017 at 22:41
  • @Kevin for some reason i can only print it using {{ item.field_body.value|raw }}. if i just print .value then i get everything back but the html is returned as plaint text so when the page render it renders with <p> as if it were a plain text field. What is the appropriate way to print a full html field with all the applied styling in it? Commented Oct 7, 2017 at 1:07
  • Leave it as the default? ie delete the custom twig file?
    – Kevin
    Commented Oct 7, 2017 at 4:40
  • Or just do an {{ item.content }} ?
    – Hudri
    Commented Oct 7, 2017 at 9:20
  • @Hudri i have set the view mode for the field as default. I need to use a twig template file to output specific <div> tags so using {{ item.content }} has not worked because for some reason it does not output as expected (see screenshots) Commented Oct 8, 2017 at 19:53

3 Answers 3

3

This is the code I'm using inside one of my field templates to output a text field, which is used as an HTML/JS widget input box

{% for item in items %}
  <div{{ item.attributes }}>{{ item.content['#context'].value|raw }}</div>
{% endfor %}

Should work for you, I guess you'll have to remove the |raw filter for your case. (But usually it is not the recommended way to output fields this way.)

1
  • i didn't think to use the #context element. That works for me. Commented Oct 13, 2017 at 17:46
-1

Never use raw, it will hurt you, use this instead

{{ {
    '#type': 'processed_text',
    '#text':  item.content['#context'].value,
    '#format': 'rich_text',
} }}
-1

I agree with the answer of Raiika. I would up-vote it, but I don't have enough reputation :)

If you want to have the #format dynamic based on which "Text format" the user selected and not force the "rich_text", you can use something like that:

{{ item.field_body.0['#format'] }}

It depends a little of the structure of the field and if you have a multi-field, but in my case it was like that.

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.