How to include context variable inside ui-template CSS

Hi,

I have the following inside a ui-template node:

<template>
    <span class="statusLabel">{{msg.statusText}}</span>
</template>

<style>
    .statusLabel {
        text-align: center;
        width: 20%;
        background: {{msg.statusLabelColor}};
        padding: 10px;
        color: white;
        border-radius: 5px;
        margin-bottom: 10px;
    }
</style>

Both msg.statusText and msg.statusLabelColor are strings, wired into the template node.
msg.statusText is rendered fine, but msg.statusLabelColor is not rendered inside the CSS, so the background color is not set when the page loads.

Why does this not work?

The {{ }} injection only works within the <template /> tags.

In order to assign a dynamic background-color, you can use Vue's dynamic binding like so:

<template>
    <span class="statusLabel" :style="{'background-color': msg.statusLabelColor}">{{msg.statusText}}</span>
</template>
1 Like

Works perfectly, thank you!

Is it considered better to change the color directly, or to change the class and specify the color for the classes separately via css?

If its just a one off example, then changing the color directly is fine.

If you have multiple instances of where that dynamic styling is required, then the class approach is cleaner as it centralises the styling definition.

[Opinion]
In an ideal world , we should always use classes to separate content from presentation. Especially for re-use, but for single one off tweaks, an inline style is sometimes "enough".
[/Opinion]

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