How to override Trix HTMLSanitizer to allow span tags with class

Viewed 915

I need to allow span tag with class in the trix editor.

I could achive adding span tag by

 Trix.config.textAttributes.span = {
        tagName: "span",
        inheritable: true
 };

But I can't get class on span it is still getting stripped by the Trix.HTMLSanitizer I guess.

I also tried with

 Trix.config.textAttributes.span = {
        tagName: "span",
        inheritable: true,
        parser: false
 };

//and


 Trix.config.textAttributes.span = {
        tagName: "span",
        inheritable: true,
        parser: (element) => {
         element.allowedAttributes = 'class';
        }
 };

Can't figure out how to override the Trix.HTMLSanitizer to allow something like <span class="my-class">value</span> to show up styled in the editor.

1 Answers

I had the same need and ended up using a hack to work around the problem: I restyled the .trix-content del element in CSS. This only works if you just need a single custom style, though. (I could do this because I didn't need the strikethrough formatting, so I could (ab)use that tag.)

To make it nicer, I then replaced the del tag with a proper span class="xxx" in the content whenever I needed to display the text anywhere other than in the Trix editor itself. That is, I used del internally to mark up, store and edit/update the content, and swapped it out for a proper span to display to the user outside the editor.

On creation of the rich-text content, to mark it for highlighting:

def create
  ...
  object_params[:content].gsub!(/foo/i, '<del>\0</del>')
  ...
end

Then, when loading it for display outside the editor:

@new_content = @object.content.to_s.gsub(/<del>/i, '<span class="highlight">').gsub(/<\/del>/i, '</span>').html_safe

And the SCSS:

// Trix-editor

.trix-content {
  del {
    background-color: $yellow;
    text-decoration: none;
  }
}

.highlight {
  background-color: $yellow;
}

This may not do what you need and is a bit nasty in any case. It would be great if Trix could support arbitrary span tags!

(FWIW, my need was to scan the text file and highlight certain words for the user.)

Related