Power Apps – Using color variables in HTML

In Power Apps you can add HTML blocks. Like this:

What if I want to store the color in a variable though? A good practice is to store the colors etc. you use as variables. So, I have a variable defined like this in the OnStart of the app.

The first thing to do would be to split the HTML code like this, in three parts:

What I want to do is replace the blue with the variable. I can’t just do the following:

This gives an error because the variable isn’t a text, it represents a color.

So what can we do here? As part of figuring this out I realized the JSON function can take various inputs and return a text representation. (Quite interesting actually! This isn’t what I wasn’t expecting with the JSON function).

So in my case JSON(gblColorMagenta) is all I need to do. Like this:

And it works!

Then I hit upon another edge case. What if I had a style element instead? Like this:

I can rewrite it like earlier:

And while I get no error, it doesn’t seem to work. The color doesn’t actually change.

I am not sure why. I suspect it might be something to do with the quotes. The style is encolosed within single quotes, and I think JSON(gblColorMagenta) adds double quotes and that’s tripping Power Apps.

So let’s try stripping that.

Notice the Substitute function takes """" as the text to replace. 4 double quotes. The first and last are required coz it needs double quotes. Single quotes don’t work, they give an error. And then I am adding two double quotes coz that seems to be the way to escape this. (I know this from working with Graph API).

That works, by the way!