The image is not displaying if debug mode is true because there is wrapper of html comments like following. So we do not need the wrapper for specific fields.

We need to
Change the code from

style="background:url(<!-- THEME DEBUG -->
<!-- THEME HOOK: 'views_view_field' -->
<!-- BEGIN OUTPUT from 'core/modules/views/templates/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' -->
  http://local.oit-drupal8-new.com/sites/default/files/2016-01/id_banner_img.jpg

<!-- END OUTPUT from 'modules/contrib/image_url_formatter/templates/image-url-formatter.html.twig' -->
<!-- END OUTPUT from 'core/modules/views/templates/views-view-field.html.twig' -->)repeat"

to

style="background:url(http://local.oit-drupal8-new.com/sites/default/files/2016-01/id_banner_img.jpg)repeat"

Support from Acquia helps fund testing for Drupal Acquia logo

Comments

mukesh.dev created an issue. See original summary.

mukesh.dev’s picture

Issue summary: View changes
mukesh.dev’s picture

Title: Remove HTML Debug Comment from a particular field in debug mode » Remove HTML Debug Comments from a particular field in debug mode
mukesh.dev’s picture

I have created a twig filter named 'remove_html_comments' to solve this issue.

In Twig, I used this as following.

{% set url  = rows[0].columns.field_top_banner.content[0].field_output['#markup'].__toString() %}
<div class="banner device-height " style="background:url({{ url|remove_html_comments }})repeat" >
mukesh.dev’s picture

Issue tags: +Filter string, +Remove Html Comments from string in twig

Version: 8.0.x-dev » 8.1.x-dev

Drupal 8.0.6 was released on April 6 and is the final bugfix release for the Drupal 8.0.x series. Drupal 8.0.x will not receive any further development aside from security fixes. Drupal 8.1.0-rc1 is now available and sites should prepare to update to 8.1.0.

Bug reports should be targeted against the 8.1.x-dev branch from now on, and new development or disruptive changes should be targeted against the 8.2.x-dev branch. For more information see the Drupal 8 minor version schedule and the Allowed changes during the Drupal 8 release cycle.

zerolab’s picture

Status: Active » Needs review
frogdog_tech’s picture

would love to see this in core

Nikhilesh Gupta’s picture

Version: 8.1.x-dev » 8.2.x-dev
FileSize
1.2 KB
zerolab’s picture

Status: Needs review » Needs work
+++ b/core/lib/Drupal/Core/Template/TwigExtension.php
@@ -155,6 +155,9 @@ public function getFilters() {
+      ¶

Unnecessary spaces

+++ b/core/lib/Drupal/Core/Template/TwigExtension.php
@@ -374,6 +377,18 @@ public function escapePlaceholder($env, $string) {
+   * @param $string

Needs data type. See https://www.drupal.org/coding-standards/docs#param

+++ b/core/lib/Drupal/Core/Template/TwigExtension.php
@@ -374,6 +377,18 @@ public function escapePlaceholder($env, $string) {
+   * @return string|null

Missing return description

Version: 8.2.x-dev » 8.3.x-dev

Drupal 8.2.0-beta1 was released on August 3, 2016, which means new developments and disruptive changes should now be targeted against the 8.3.x-dev branch. For more information see the Drupal 8 minor version schedule and the Allowed changes during the Drupal 8 release cycle.

pminf’s picture

Instead of introducing a new twig filter we should improve the existing filter strip_tags to remove comments. Because thats what developers are expecting – analog to PHP's strip_tags function:

HTML comments and PHP tags are also stripped.

ckaotik’s picture

The default Twig striptags filter seems to be based on the php strip_tags equivalent. Thus we can provide a list of allowed tags and can check for empty using something like this: my_variable|render|striptags('<img><drupal-render-placeholder>')|trim|length > 0 :) Not the easiest solution, but so far it does what I need.

mukesh.dev’s picture

zerolab’s picture

+++ b/core/lib/Drupal/Core/Template/TwigExtension.php
@@ -1,4 +1,6 @@
+<?php

Triple php start tag.

+++ b/core/lib/Drupal/Core/Template/TwigExtension.php
@@ -170,7 +172,8 @@ public function getFilters() {
+	  new \Twig_SimpleFilter('remove_html_comments', [$this, 'removeHtmlComments']),

Looks like a tab.

mukesh.dev’s picture

landsman’s picture

Hello mukesh.dev!
Your patch has good idea but do same as default filter: "|render|striptags".

My show case:

{% set article_type = content.field_article_type|render|striptags %}

Returns: via: {{ dpm(article_type) }}

"""
\n
\n
\n
\n
\n
\n
Fotogalerie\n
\n
\n
\n
"""

And your patch return same result.
We need remove these new lines "\n" ...

landsman’s picture

----- Bad patch :( moderators please remove this comment -----

landsman’s picture

I was added it to our module: DrupalTwigFood

Version: 8.3.x-dev » 8.4.x-dev

Drupal 8.3.0-alpha1 will be released the week of January 30, 2017, which means new developments and disruptive changes should now be targeted against the 8.4.x-dev branch. For more information see the Drupal 8 minor version schedule and the Allowed changes during the Drupal 8 release cycle.

ay13’s picture

Adding the trim filter will remove all the excess whitespace and new lines.
{% set article_type = content.field_article_type|render|striptags|trim %}

Version: 8.4.x-dev » 8.5.x-dev

Drupal 8.4.0-alpha1 will be released the week of July 31, 2017, which means new developments and disruptive changes should now be targeted against the 8.5.x-dev branch. For more information see the Drupal 8 minor version schedule and the Allowed changes during the Drupal 8 release cycle.

osopolar’s picture

Status: Needs work » Needs review
FileSize
1.53 KB
+++ b/core/lib/Drupal/Core/Template/TwigExtension.php
@@ -393,6 +394,20 @@ public function attachLibrary($library) {
+  public function removeHtmlComments($string) {
+    $output = preg_replace('/<!--(.|\s)*?-->/', '', $string);
+    $output = str_replace(array("\n", "\r"), '', $output);

The str_replace removes to many line breaks, so that the $output is just one line. What a bout adding \s* to the end of the regular expression in preg_replace instead of using str_regreplace?

#10 and #15 seems to be fixed too.

Status: Needs review » Needs work

The last submitted patch, 23: Remove-HTML-Comments-From-String-2672656-23.patch, failed testing. View results

bdanin’s picture

#21, |render|striptags|trim worked very well for me, many thanks!

AdamPS’s picture

maxplus’s picture

Thanks,
working with |render|striptags|trim also worked for me to render a field inside a paragraph used as css class.
Without the |render|striptags|trim the complete theme debug code cluttered the rendered field and broke my html during development...

Version: 8.5.x-dev » 8.6.x-dev

Drupal 8.5.0-alpha1 will be released the week of January 17, 2018, which means new developments and disruptive changes should now be targeted against the 8.6.x-dev branch. For more information see the Drupal 8 minor version schedule and the Allowed changes during the Drupal 8 release cycle.

robbdavis’s picture

#21 worked for me also; although, I did not need the "| render |" filter. Code to get pure url looks like this:

{% set stripped_img_url = fields.uri.content | striptags | trim %}
{% set img_url = stripped_img_url | image_style('image700x450') %} //Using twig_tweaks to add image filter
<img src="{{ img_url }}">

Gotta say that this was a super annoying issue to deal with; I hope the fix gets added to core soon.

yogeshmpawar’s picture

Assigned: Unassigned » yogeshmpawar
yogeshmpawar’s picture

Assigned: yogeshmpawar » Unassigned
Status: Needs work » Needs review
FileSize
1.49 KB

Re-rolled the patch #23 against 8.6.x branch.

lpeabody’s picture

One thing to note with striptags is that it loves to html encode strings. So if you end up outputting a URL with ampersands in a query string it's going to break the query string portion. This is where striptags breaks down for me. In particular this happens when I'm outputting an image with a cache busting token + a focal point token. So I need an alternative solution to striptags in this instance.

lpeabody’s picture

What if this was solved by a sort of whitelist/blacklist where you could specify entity type, bundle, view mode, and field name to not output debug commentary on? Thoughts?

Version: 8.6.x-dev » 8.7.x-dev

Drupal 8.6.0-alpha1 will be released the week of July 16, 2018, which means new developments and disruptive changes should now be targeted against the 8.7.x-dev branch. For more information see the Drupal 8 minor version schedule and the Allowed changes during the Drupal 8 release cycle.

code-brighton’s picture

FileSize
2.66 KB

For anyone like me wanting this functionality and not sure whether to go for this patch until things have been settled on. I created a little module using the method in the patch (thanks folk)

1. Install module
2. Add something like this in your twig

{{ commentStripper(your_stuff) }}

e.g.

{{ commentStripper(fields.title.content) }}
pminf’s picture

Status: Needs review » Closed (outdated)

Don't know when or how this was fixed but using Drupal 8.7.0-dev I can get rid of all html tags including comments by just using striptags. I did not applied any of the patches posted here. At the time this issue was created striptags was not removing html comments.

Normal output without striptags:

{% set foo = content.field_foo|render %}
Foo: [{{ foo }}]
Foo: [

<!-- THEME DEBUG -->
<!-- THEME HOOK: 'field' -->
<!-- FILE NAME SUGGESTIONS:
   * field--node--field-foo--page.html.twig
   * field--node--field-foo.html.twig
   * field--node--page.html.twig
   * field--field-foo.html.twig
   * field--integer.html.twig
   x field.html.twig
-->
<!-- BEGIN OUTPUT from 'core/themes/classy/templates/field/field.html.twig' -->

            <div class="field field--name-field-foo field--type-integer field--label-hidden field__item">42</div>
      
<!-- END OUTPUT from 'core/themes/classy/templates/field/field.html.twig' -->

]
  

Plain output with striptags:

{% set foo = content.field_foo|render|striptags %}
Foo: [{{ foo }}]
Foo: [






            42
      


]

Plain and trimmed output with striptags and trim:

{% set foo = content.field_foo|render|striptags|trim %}
Foo: [{{ foo }}]

Foo: [42]

pminf’s picture

Status: Closed (outdated) » Fixed
mlncn’s picture

There should be a way to override debug comments on a per-field basis without stripping tags but, yeah, that never directly came up in this issue so i'm just leaving this comment as moral support for anyone who wants to open a new issue about that!

Status: Fixed » Closed (fixed)

Automatically closed - issue fixed for 2 weeks with no activity.

nortmas’s picture

FileSize
1.49 KB

Also, remove line breaks.

OnkelTem’s picture

My few cents.
This issue is just crazy. Really.

What you guys do seems as a sort of nonsense. Instead of picking the source values of the fields, you first render them and then trying to get rid of commens, eh?

You'd laugh but I came here because I have similar issue. But with views. With damned views which just don't provide source values for the fields in 'views-view-fields' templates. If you're not coupling with Views like me atm, try to borrow source values of the fields, not from their rendered result.

chharvey’s picture

This worked for me:

<img src="{{ fields.field_image_url.content|striptags|trim }}" alt="{{ fields.field_image_alt.content|striptags|trim }}"/>

See the docs for the |striptags and |trim filters.

pminf’s picture

@OnkelTem (#41) Of course using the source value is a lot cleaner but sometimes it does not output the desired format. Think about reference fields to images for example: By using the source value you would get the entity id instead of the url and you would need to build up the correct path to the image style file with twig functions by yourself (although it has already been done "by core").

hawkeye.twolf’s picture

@mlncn, re:

There should be a way to override debug comments on a per-field basis without stripping tags but, yeah, that never directly came up in this issue so i'm just leaving this comment as moral support for anyone who wants to open a new issue about that!

Isn't that exactly what this issue is about? I believe this issue should be re-opened, as stripping HTML comments without stripping the rest of the rendered tags is important.

BTW, for those who do use striptags, make sure you whitelist drupal-render-placeholder, in addition to any other tags your content might contain. E.g.,

{{ content.field_foo|render|striptags('<drupal-render-placeholder>') }}
robert_t_taylor’s picture

#21 simplified an issue I was having trying to escape a variable to run it through a custom filter. Thanks!

orlando.thoeny’s picture

Since this issue was created in 2016, and it seems like it might take a while (or it will never happen) for this to land in core.
I used the patch and created a module out of it: https://www.drupal.org/project/twig_remove_html_comments

Alen Simonyan’s picture

For example in views template you can use -
{{ fields.field_name.content | striptags | trim }}, no patch needed I think:
In this case | striptags cuts all tags including HTML comments.
For Images you can use -
{{ fields.field_author_image.content | render | striptags('<img>') | trim | raw }}:
In this case | striptags cuts all tags except <img> tag

Martijn de Wit’s picture

Referring to meta issue. #953034: [meta] Themes improperly check renderable arrays when determining visibility.
Didn't know there was a "similar" discussion.

hawkeye.twolf’s picture

@Alen Simonyan, note that striptags does not suffice as we need a generic way to remove HTML comments without also removing other tags, even when we don't know those tags will be.

bdanin’s picture

The drupal/twig_remove_html_comments from #46 doesn't work well because it doesn't work for arrays. I've found that using entity.field_name.value tends to work quite well. For example in a node template, I use node.field_name.value or in a paragraph template paragraph.field_name.value.

orlando.thoeny’s picture

@bdanin please create an issue in the module issue queue if you need that functionality.
However I only intended it to be a temporary solution (preferably). Until something for this issue is worked out for Core.

hawkeye.twolf’s picture

@bdanin, printing node data directly in field templates is not advised, both for security and because it cuts off functionality provided by field formatters, etc. Use render arrays provided by the drupal render API wherever possible.

The solution is to call |render on your render array before passing it to |remove_html_comments. E.g.,

{{ content.field_name|render|remove_html_comments }}
bdanin’s picture

@hawkeye.twolf, thanks for this info! @orlando.thoeny, I've created an issue in the module queue.

draganFSD’s picture

Issue tags: -

Instead of
you can put just empty field...

{{ article_type|replace({'\r\n': '<br>'}) }}

cswan’s picture

#21, |render|striptags|trim worked for me. Thank you!

nortmas’s picture

FileSize
1.49 KB

New patch for the core 9.4.5.

camslice’s picture

IMHO opinion this filter is needed, however it should target Twig specifically and properly process HTML entities.

Can we please re-open this issue?

In its current form, the result of |remove_html_comments is the same as |striptags|trim.

For example, take a field value of "Twelve O'Clock".

Both |striptags|trim and |remove_html_comments output the same result:

Twelve O&#039;Clock

I suggest 2 changes to make this filter worthwhile in its own right:

  1. Rename it to |strip_twig_debug or maybe |remove_twig_debug
  2. Process HTML entities

If processing HTML entities feels too invasive, we could always pass an optional argument allowing people to prevent HTML entity processing.

Currently, the only viable option is the twig_htmlspecialchars_decode module, resulting in quite a long and clumsy filter chain ':[]

|striptags|trim|twig_htmlspecialchars_decode
Martijn de Wit’s picture

@camslice did you try the https://www.drupal.org/project/twig_field_value module?

scott_euser’s picture

You can also use https://www.drupal.org/project/twig_remove_html_comments which removes the html comments without removing the actual markup inside the nested template. I have suggested an update to the module homepage as it is outdated referencing this issue #3421810: Module homepage description is in need of an update with incorrect information.

quietone’s picture

Status: Closed (fixed) » Closed (outdated)

@scott_euser asked that the status of this issue be change to 'closed won't fix'.

I have searched the issue and there is no commit here. I skimmed through the comments and do not see anything, like a documentation change, to suggest that this has been fixed. #36 closed this as outdated and the next comment changed the status to 'Fixed'. That was the mistake. If I knew the issue where this was fixed there is a possibility that this could be closed as a duplicate and credit transferred. But, there is no reference to another issue so 'closed outdated' is the status to use.

Also, noting that there are comments suggesting the use of contrib projects, #57, #58, #59

I am restoring the status from #36

Edit: s/know/knew/

scott_euser’s picture

Thanks @quietone. In case people come across this issue because of debug comments added within formatted text, I separately raised #3421843: filter_autop should ignore twig.config debug html comments with a merge request proposing a solution.