March 21, 2018 | Comments
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
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:
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:
Here’s a quick look at each of the steps:
ias our iterator. This will increase in single increments starting at
1and finishing at
5— the start and end values are defined in the
forloop declaration I check to see if the counter
less than or equal toto
include.ratingwhich 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.
forloop 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).
starsstring wrapped in a
spanfor 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.