skip to Main Content

Desired result

Content editors can enter hexadecimal values in Shopify for a background-color. How can you check with Liquid template’s control flow if a given input is a valid hexadecimal?

The regex that needs to be implemented:

^#(?:[0-9a-fA-F]{3}){1,2}$

The Liquid snippet where it should be added:

<div class="a-module" style="background-color: {{ bg_color }};">
  ...
</div>

The variable bg_color may only be a hexadecimal including the pound # character.

How can above be achieved with regex?

Other solutions?

If this is not possible what are other methods to match a string in liquid templates?

Research

I could not find much about regex in liquid templates.

There is this issue: Regex for matching a tag in a Liquid template : ">" inside html tag

But I do not understand how it is to be implemented.

2

Answers


  1. What about create your own filter. And in this filter checking hexadecimal.

    /^#[0-9a-f]{3,6}$/igm
    

    https://github.com/Shopify/liquid/wiki/Liquid-for-Programmers#create-your-own-filters

    Login or Signup to reply.
  2. There is no regex in Shopify liquid, so there is no way to check it that way.

    A better approach will be to use one of the color filters.

    You can do something like this:

    {% assign is_color = bg_color | color_to_rgb  %}
    {% if is_color %}
      It's color
    {% endif %}
    

    Where if the color is valid it will return a rgb output, but if it’s not it will return a null result making the variable false.

    If you really need to use regex, the only option is to rely on Javascript and handle it once the DOM is ready.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search