Is it possible to format spans in a RichText?

I am trying to add a RichText with some formatted html so it looks like this:
image

I was able to get the different color and size shown in the bitmap by adding this in the native libraries section:

<style>
  .anvil-rich-text span {
    color: gray;
    font-size: x-small;
  }
</style>

And this in the content of the RichText:

f'{part}<span>({qty})</span>'

All of this works, but I’m limited to using the same style for all the spans inside the RichText.

I would like to be able to define different styles for different spans or different RichTexts. I have tried all of the below, but all of the attributes of the span tag are stripped:

f'{part}<span style="color:gray;font-size:x-small;">({qty})</span>'
f'{part}<span class="small-and-gray">({qty})</span>'
f'{part}<span name="small-and-gray">({qty})</span>'
f'{part}<span id="small-and-gray">({qty})</span>'

What is the best way to play with text formatting and change font, color, size, etc. of parts of a text inside a RichText?

Hi @stefano.menci,

You can create slots in your RichText using { }, add labels to those slots and then format those separately, as described here. Does that do what you’re looking for?

I don’t think slots can work for me, because everything is created dynamically.

Then the content of the RichText gets the value returned by this function:

  def panel_list(self):
    rows = []
    for panel in self.summary_view():
      n = panel.qty_in_crate(self.crate_number)
      if n == 1:
        rows.append(panel.number)
      else:
        rows.append(f'{panel.number}<span class="small-and-gray;">({n})</span>')
    return ' '.join(rows)

I would like to create more functions similar to this one where bits of the string are color coded.

The rich text component provides a safe subset of HTML. It looks like that safe subset isn’t enough for what you’re trying to do.

If the content you’re dynamically creating can be trusted (e.g. doesn’t itself contain HTML/CSS/Javascript), you can just use an HTML form as a component and set the HTML property on it to get access to the full range of HTML/CSS options.

That assumes also that you aren’t using any other features of the rich text component that aren’t available in a normal HTML form.

Now that I read this I remember that I have an old custom component that I made for this very reason!

I saw the new RichText and forgot about my old component, but in cases like this it’s just more flexible and still good.

1 Like

I did the same thing with the new component, and ultimately decided it wasn’t right for my use case, where I was just displaying arbitrary trusted HTML/CSS. The rich text component really seems to shine when you’re mixing interactive components with formatted text.

1 Like