Add an ID or CLASS to an image (within a post)

My goal is to add some banners to Not Logged In Users within a post. The CSS works great, but I can’t apply it to any images within the post.

Is there currently a way to add an ID or CLASS to an image (within a post)? So far I have tried:

![Title|690x85](/image.png#example)

And I’ve tried putting in raw HTML

<img id="example" src="image.png" alt="image" width="690" height="85">

Both methods result in the ID or CLASS being stripped out of the actual rendering of the page.

You can’t by default. There’s only a few attributes that are whitelisted for <img> tags. You can find those here:

https://github.com/discourse/discourse/blob/master/app/assets/javascripts/pretty-text/white-lister.js.es6#L170-L173

Whitelisting specific classes can be done but would require a plugin.

How often do you plan on using this? You might be able to make something work with a theme component but the implementation will depend on your use case. Can you share a specific example of what you’re trying to do?

for example, you can wrap the image in something like

<div data-theme-banners>
  <img src='foo'>
</div>

then you can use the selector

[data-theme-banners] img
2 Likes

So, it looks like the ID is being stripped out my DIV as well.

<div id="example">
    <a href="#">
        <img src="image.png" alt="image" width="690" height="85">
    </a>
</div>

This was the end goal I was attempting. Which is done. I just don’t want it to appear to logged in users, which is where I was relying on the CSS

Correct, <div> tags also have very specific properties that are whitelisted. Those can be found here:

https://github.com/discourse/discourse/blob/master/app/assets/javascripts/pretty-text/white-lister.js.es6#L141-L152

That file - it is the same one from my earlier post - contains all the whitelisted markup allowed in the composer so have a look around to see what is allowed. Anything not on that list will be stripped out to prevent abuse.

The <html> tag has a CSS class added to it to when the user is not logged in. That class is anon. You can use that class to selectively show the banners. So something like this in your post:

<div data-theme-banners>
  <a href="#">
    <img src="foo">
  </a> 
</div>

and this in your theme

html:not(.anon) .cooked [data-theme-banners] {
  display: none;
}

and that would ensure that the element is only visible to users who are not logged in.

3 Likes

Sir, you are a legend.

3 Likes

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.