apostrophecms / sanitize-html

Clean up user-submitted HTML, preserving whitelisted elements and whitelisted attributes on a per-element basis. Built on htmlparser2 for speed and tolerance
MIT License
3.68k stars 349 forks source link

Question: how to wrap an <img> tag into <a> tag? #554

Closed geantas closed 1 year ago

geantas commented 2 years ago

Question or comment

I am looking to wrap an tag into tag. However, the documentation does seem to describe such functionality, only trimming tags. Any chance you could suggest me how it's done? My goal is that every would have a link that'd actually open that image in a new tab.

BoDonkey commented 2 years ago

Howdy, You can accomplish this by extending the allowed tags. By default, the '' tag isn't included. Depending on use case, you can pass it on a single call to sanitizeHtml:

import sanitizeHtml from 'sanitize-html';

sanitizeHtml(dirty, {
allowedTags: sanitizeHtml.defaults.allowedTags.concat(['img])
});

Or write a helper:

import sanitizeHtml from 'sanitize-html';

const mySanitize = (dirty) => {
  return sanitizeHtml(dirty, {
    allowedTags: sanitizeHtml.defaults.allowedTags.concat(['img'])
  });
};

Both of these approaches will return <a href="#"><img src="http://unsplash.com" /></a> if passed something like: "<a href='#'><img src='http://unsplash.com'></img></a>"

Hope this helps, Bob

geantas commented 1 year ago

Thank you for your reply, @BoDonkey. But it's something a little different I am looking for. I am aware that the <img> tag is not included in allowed tags and I have added it to allowedTags. What I am looking for is to wrap that <img> tag with an <a> tag, so whenever the image is submitted, it will have a link to it. For example, I receive <img src="http://unsplash.com" /> as a string. I want to make it wrapped in <a> tag, like this:

<a href='#'>
   <img src='http://unsplash.com' />
</a>

Do you think it's possible to achieve that with sanitizeHtml?

BoDonkey commented 1 year ago

Hi @geantas - I think this would be possible in sanitize-html, but it would probably be easier to use "cheerio" as a second step after sanitize-html. The cheerio package is likely already installed in your project and is well suited to manipulating the DOM structure on the server.

boutell commented 1 year ago

@BoDonkey gives good advice here. Just a quick note that cheerio might or might not already be present since sanitize-html is often used outside of ApostropheCMS, and in any case you should explicitly npm install anything you plan to use in your project rather than relying on sub-dependencies being present, although it's true you only pay for the space once if it's already a sub-dependency.

stale[bot] commented 1 year ago

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.