Hi fellow Lookers,
In this post, I want to share my solution and highlight some issues when creating a star rating from a numeric input.
Let’s say I have a dimension called “conversation_rating” that can hold values from 1 to 5.
I want to take the input and convert it into a star rating using the numeric input to determine the number of colored stars.
To show a star, let’s use the unicode ★ character.
dimension: conversation_rating {
hidden: no
type: number
sql:CAST(${TABLE}.ConversationRating AS FLOAT) ;;
html:
★ ;;
}
Next, I have to color it yellow. I tried to add color to the span tag, but to no success. I found success when I used a font tag to change the color as shown in the HTML parameter documentation.
dimension: conversation_rating {
hidden: no
type: number
sql:CAST(${TABLE}.ConversationRating AS FLOAT) ;;
html:
<font color="orange">★</font> ;;
}
The last step is to repeat the stars depending on the initial value. I first thought to create a nested case statement, but that seemed to much work on second thought.
So I came up with a for-loop that gives us the desired outcome:
dimension: conversation_rating {
hidden: no
type: number
sql:CAST(${TABLE}.ConversationRating AS FLOAT) ;;
html:
{% for i in (1..5) %}
{% if i > value %}
★
{% else %}
<font color="orange">★</font>
{% endif %}
{% endfor %} ;;
}
The logic is to show an orange star unless the loop count is greater than the conversation rating. We can access the rating using liquid variable {{value}}. The double parentheses can be omitted when it is used in liquid {% %} tags. So if the input is 4, it will show 4 orange stars and 1 dark one, in that order.
Below you can see what it looks like in a dashboard.
Mission complete!
Happy coding,
blue
Hello, what about the mid terms? Like 3.5, 4.5? (Half star)
Thanks!!