sneha
sneha

Reputation: 445

Not able to Set default CSS variables from model object in Thymeleaf

I'm setting CSS font variables inside a style tag in a Thymeleaf template. The font values are coming from the model object. I also want to apply a default color, in case the model attirbute is not there. I am using elvis operator to pick the default value Elvis Operator link

But When I render the template ,it is searching for brandingConfig then themeConfig and then fontName but fontName is not present inside themeconfig .So instead of picking the default value it is throwing an error .Below is the error which I am getting

org.thymeleaf.exceptions.TemplateProcessingException: Exception evaluating SpringEL expression: "brandingConfig?.themeConfig?.fontName".

org.springframework.expression.spel.SpelEvaluationException: EL1008E: Property or field 'fontName' cannot be found on object of type 'java.util.LinkedHashMap' - maybe not public or not valid?

Below is my style tag. I am new to Thymeleaf, what should I do differently here?

<style th:inline="text">
:root {
    --font-name: [[${brandingConfig?.themeConfig?.fontName}?: 'Proxima Nova']];
    --font-url: [[${brandingConfig?.themeConfig?.fontUrl}?: 'https://fonts.googleapis.com/css?family=Proxima+Nova']];
}

Upvotes: 0

Views: 203

Answers (1)

Metroids
Metroids

Reputation: 20477

If works for me with these expressions:

<style th:inline="text">
:root {
    --font-name: [[${brandingConfig?.themeConfig?.get('fontName')}?: 'Proxima Nova']];
    --font-url: [[${brandingConfig?.themeConfig?.get('fontUrl')}?: 'https://fonts.googleapis.com/css?family=Proxima+Nova']];
}
</style>

I'm not sure exactly why, but I think it's something to do with the way the safe navigation operator works with Map keys...

Upvotes: 1

Related Questions