Originally this was in a views field rewrite but i have since moved it to

views-view-fields--[view name]--[machine ID].html.twig

And behaviour seems to be the same:

 <a href="{{ fields.path.content}}" class="menu-item">{{fields.title.content}}<span data-background-image="{{ fields.field_image.content}}"></span></a>

This renders fine when twig debug is set to false in development.services.yml When twig debug is turned on, the markup becomes badly broken.


<span data-background-image="

    <!-- THEME DEBUG -->
    <!-- THEME HOOK: 'views_view_field' -->
    <!-- BEGIN OUTPUT from 'themes/mytheme/templates/views/views-view-field.html.twig' -->

    <!-- THEME DEBUG -->
    <!-- THEME HOOK: 'image_url_formatter' -->
    <!-- BEGIN OUTPUT from 'modules/contrib/image_url_formatter/templates/image-url-formatter.html.twig' -->
    <!-- END OUTPUT from 'modules/contrib/image_url_formatter/templates/image-url-formatter.html.twig' -->

    <!-- END OUTPUT from 'themes/mytheme/templates/views/views-view-field.html.twig' -->


HTML does not support <!-- --> inside tags, which seems to be the core issue. Is there a workaround to this, or it's just a limitation of Twig debug?

  • I've run into this issue as well. To get around it, I was using a Chrome plugin called "Drupal template helper" (which moves the debug marrkup to its own pain in Chrome) but sadly, the plugin is now broken. See this issue for more info: github.com/arshad/drupal-template-helper/issues/8 – Danny Englander Dec 20 '16 at 15:06

You can apply |render|striptags|trim twig filters:

<a href="{{ fields.path.content|render|striptags|trim }}" class="menu-item">{{ fields.title.content }}<span data-background-image="{{ fields.field_image.content|render|striptags|trim }}"></span></a>

If you want to save (not delete) for example div or img tags you can also write:

{{ fields.field_image.content|render|striptags('<div>, <img>')|trim }}

Seen here https://www.drupal.org/node/2672656#comment-11821896

  • This is great. Previously I was altering $variables['fields'] values to remove the twig debug output on some fields. – Web Assistant Feb 27 '18 at 15:20
  • How can I do this when I have a field in a view? – 0711master Jan 6 '19 at 1:56
  • 2
    It's such a shame that this is seemingly the best way around this. A fix for a problem in the development environment that, without yet more messing around, will end up in production too. 3 unnecessary function calls to fix a problem that doesn't even exist in that environment. – Dan Abrey May 13 '19 at 13: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.