March 21, 2018

How to Create a Star Rating System in Liquid

I’ve recently been working on a new side–project that will feature a series of reviews. I hadn’t intended to include a star rating for each item but figured it might be a nice touch and a visual indicator as to the overall review. I wanted to make this as simple to use as possible and thankfully after a little Liquid wrangling came up with a easy implementation.

Given that I wanted to be able to use this on multiple pages I decided to make this an include file. I’ll be using this on a Jekyll powered site but you could just as easily implement this in Shopify — instead of passing in a front matter value you could use a custom field value stored against a product.

Here’s the contents of _includes/star-rating.html:

{% for i in (1..5) %}
{% if i <= include.rating %}
{% assign stars = stars | append: '&#9733;' %}
{% else %}
{% assign stars = stars | append: '&#9734;' %}
{% endif %}
{% endfor %}
<p class="star-rating">Rating: <span>{{ stars }}</span></p>

To make this work I include it in the reviews .md file and pass in a numeric value. Here’s how I will be using it in my new project:

{% include star-rating.html rating=2 %}

I’ve passed in an numeric value in this example but it could easily be a front matter value too, which would look like this:

{% include star-rating.html rating=page.rating %}

What’s Going On?

Here’s a quick look at each of the steps:

  1. First I create a simple for loop with a variable called i as our iterator. This will increase in single increments starting at 1 and finishing at 5 — the start and end values are defined in the for declaration using (1..5).
  2. After the for loop declaration I check to see if the counter i is less than or equal to to include.rating which is the value passed into the include file. In the first example above this is 2. If this resolves to true we add ★ (a filled star) to a variable called stars. If it evaluates to false we add ☆ (an unfilled star) to the string. I decided against using images for this as it’s a little messy and HTML entities are very easy to style with CSS there seemed no benefit.
  3. Once the for loop has finished we should be left with solid stars equal to the value we passed in (i.e. our rating), and the remaining (up to 5 — our top rating) will be outlined (unless it’s a 5-star review of course).
  4. Finally, I output the stars string wrapped in a span for easy CSS styling.

As I said, it’s pretty simple but gives the visual result needed. Using front matter to store the value should also allow filtering later, if that was something you desired.

This article was written by Keir Whitaker and published on March 21, 2018. All articles are available in the blog archive and you can subscribe to the RSS Feed for updates. Have a question? Discuss this article with me by email.