Dynamic foreground color for some words being displayed in the textarea

What I’m trying to do:
I have some results coming in from colab. I want to check a string for some keywords in the database and then highlight the words that are found there while displaying this text in a textarea.
How can I do this dynamic coloring?

What I’ve tried and what’s not working:
I tried using .foreground but it doesn’t seem to work.

Code Sample:

# this is a formatted code snippet.
# paste your code between ``` 

class Form2(Form2Template):
  def __init__(self, job, **properties):
    # Set Form properties and Data Bindings.
    self.init_components(**properties)
    self.job = job # passed from google colab
    self.PopulateText()
  
  def PopulateText(self):
    # Any code you write here will run when the form opens.
    self.title.text = self.job['title']
    self.location.text = self.job['location']
    self.MatchKeywords()
    
    self.src.text = self.job['via']
    self.company_name.text = self.job['company_name']
    
  def MatchKeywords(self):
    colors = {0:'black', 1:'green'}
    for word in self.job['description']:
        self.description.foreground = colors[word in keywords]
        self.description.text += word
        self.description.focus()

Clone link:
share a copy of your app

Do you need the text to be editable?

If not, create an HtmlTemplate component (you have to do this in code, it isn’t in the component panel on the right). You can set its .html property and it’ll display as HTML. You can build your string as HTML formatted text, e.g. This is <span style="color: red">red text</span>.

Here’s a clone that demonstrates using the HtmlTemplate component: Anvil | Login

If you need the text to be editable, you’re looking at a Javascript editor. The normal text area doesn’t allow individual formatting. Maybe look at the Quill editor in Anvil Extras? I haven’t used it, but you might be able to get the formatting you want out of it.

A quick dirty trick is to use a RichText and wrap the words with back ticks. Something like this:

"The `special` word"

This gives a quick solution for one color out of the box.

If one color is enough, but you don’t like how it looks, you can play with the css.

If you need more than one color, then this quick dirty trick is not for you.

1 Like