Home > OS >  Is there a way to use a field's value in the Model to set a style attribute dynamically?
Is there a way to use a field's value in the Model to set a style attribute dynamically?

Time:12-01

I have created a CSHTML email template file to send alerts when a specific event is about to end (i.e. sends an alert 10-minutes before end, then at 5-minutes before end, etc.). I want to highlight the type of event (since there can be more than one) by color to differentiate the messages. What I currently have is this:

<strong style="color: {event color}">@alert.event</strong> is scheduled to end: <strong>@endEasternTime

I would like to be able to set the {event color} based on the value in @alert.event, but I'm not sure that I can. I tried to create a script in the file, but I'm not sure how to get its return value into the style tag:

<script>
    // Get the root element
    var r = document.querySelector(':root');

    // Create a function for getting a variable value
    function getEventColor(event) {
        // Get the styles (properties and values) for the root
        var rs = getComputedStyle(r);

        // Get the color associated with the event (default is the border color)
        return (event === "event1"
            ? rs.getPropertyValue('--evt1Color')
            : (event === "event2"
                ? rs.getPropertyValue('--evt2Color')
                : (event === "event3"
                    ? rs.getPropertyValue('--evt3Color')
                    : rs.getPropertyValue('--bdrColor')
                    )
                )
            );
    }
</script>

Note that I have created HTML variables in the file to match up the colors to other styles in the file (such as border-color) -- for space considerations and clarity, I'm not going to show that here.

Is there a way to do this? If not using the inline CSS above, can I update a class or id on the fly using something like the script method above and, if so, what's the best way. I appreciate any help.

CodePudding user response:

You could use if.. else..

@if (@alert.event == value1) 
{     
     <strong class="color1">
}
else if (@alert.event == value2)
{     
    <strong class="color2"> 
}
else {
    <strong class="colorn">
}

Or simpler way could be naming the classes based on your event and adding color using CSS.

<strong class="event @alert.event">

The tag has 2 classes (event and the value generated)

Lets say @alert.event = "test", then add the CSS to the class as shown below.

.event.test {
    color: <color code>
}
  • Related