How to create star rating from numeric value using HTML and Liquid

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.

Inputs

Let’s say I have a dimension called “conversation_rating” that can hold values from 1 to 5.

Screenshot 2020-06-06 at 22.31.12

Objective

I want to take the input and convert it into a star rating using the numeric input to determine the number of colored stars.

Approach

To show a star, let’s use the unicode ★ character.

 dimension: conversation_rating {
    hidden: no
    type: number
    sql:CAST(${TABLE}.ConversationRating AS FLOAT) ;;
    html:
      ★ ;;
  }

Screenshot 2020-06-06 at 21.56.17

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> ;;
  }

Screenshot 2020-06-06 at 22.08.57

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.

Screenshot 2020-06-06 at 22.29.34

Mission complete!

Happy coding,
blue

8 1 3,063
1 REPLY 1

Almada
New Member

Hello, what about the mid terms? Like 3.5, 4.5? (Half star)

Thanks!!

Top Labels in this Space
Top Solution Authors