1

My twig file is adding line breaks in the HTML which results in white spaces, as shown in this picture: Line breaks causing white spaces

In the browser inspector: Line breaks in the HTML

When I remove the line breaks in the inspector, the white spaces disappear.

The default code in the file views-view-field.html.twig is:

{{ output -}}

I have researched the problem quite a bit and tried the following already, without success:

{{ output|replace({"\n":''}) }}
{{ output|trim }}
{% spaceless %}{{ output }}{% endspaceless %}
{% spaceless %}{{ output|render|trim }}{% endspaceless %}

I'm working on Drupal 8.7.6.

Any help would be appreciated.

2 Answers 2

3

The cause of the problem is probably not the template but how the field is configured in Views. You should be able to find a solution there, even if it means you need to rewrite the field output.

If you want to try solving it in this template you have to check what is inside of output. Views usually puts the field output in a markup object. Then you have to render it first before applying twig filters:

{{ output|render|striptags|trim }}

I've also added |striptags, otherwise you would see HTML tags in plain text on the screen because they are escaped by trim.

4
  • "how the field is configured in Views" – You mean the field formatter?
    – leymannx
    Aug 12, 2020 at 8:10
  • 2
    I mean most times it is a better idea to put Twig in Views UI, not in Views templates. See drupal.stackexchange.com/a/218087/47547
    – 4uk4
    Aug 12, 2020 at 8:15
  • Many thanks for the reply. The output is comes from a Taxonomy that I created (most of them of the type "Plain Text"). I went to the Views settings and tried a few things in the Field Configurations, like "Remove whitespaces" and "Override the output of this field with custom text", trying to render the output differently. No success so far. @4k4: What did you mean with "Then you have to render it first before applying twig filters"? Would you add this line ({{ output|render|striptags|trim }}) in the Views UI or in Twig file?
    – J. Ken
    Aug 12, 2020 at 21:20
  • This is my suggestion to your attempts to trim {{ output }} in views-view-field.html.twig.
    – 4uk4
    Aug 13, 2020 at 6:24
0

The solution

{{ body|replace({"\n": "", "\r": "", "\t": ""}) }}

works for me in views Global/Custom text field. It removes new lines from the body field.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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