Creating Useful CSS Hooks in Liquid

Creating useful CSS hooks in Liquid

Many of us use theclass for CSS and JavaScript hooks and just like in WordPress it’s pretty easy to add a number of useful classes to ourelement in Shopify.

Here are a few ideas that you might find useful placing in your main (or alternate) layout file:

Add the currently rendered template name to the body class

In this example, we are using模板to return the name of the currently used template. Some examples of this are:




This can be really useful when you need to target a specific alternate template for example.

Add the currently rendered product handle to the body class

Building on this we may wish to add the current producthandleto our body class. To keep things neat and tidy we can use anifstatement to conditionally add the product handle only when we are viewing a product:

Note how I include the space before the{{ product.handle }}output tag.

If you are using alternate product templates you may wish to use thecontainsoperator instead:

Add the current page title to the body class

Some themes also add the current page title to the body element in the form of an id, building on the above our code would now look as follows:

Note in this example we are using the Liquid filterhandleizeto ensure that theidorclassthat we add is URL safe and therefore easy to reference in our CSS and JS files. For example, it will turn a page title of “Blue Jeans” into “blue-jeans”.

Add the currently viewed collection’s name to the body class

For good measure, we could even add in a check for collections and add that too:

It’s pretty easy to adjust this logic for your own purposes. Again you may wish to use thecontainsoperator if you are utilising alternate templates.

Summary

Hopefully you’ve seen how flexible Liquid is in the above examples. Being able to add a variety of classes to theelement gives us useful hooks that we can use in CSS and JavaScript.

Template Icon

Grow your business with the Shopify Partner Program

Learn more