Patrick Bollenbach

Shopify Liquid String Interpolation

While building my Shopify app Wait.li I discovered that Shopify’s Liquid has no built in interpolation function / filter.

I am storing user settings in Shopify metafields, and one setting is a string that is displayed on the Shopify storefront. This string has the possibility of including other Liquid variables (assigned previously on the page).

Attempt 1:

My metafield was string that contains the following value (notice the curly brackets):
“Hello! Today is {{ todays_date }} - thanks for shopping at my store.”

My thought process was; if the Liquid variable is already assigned, Liquid should render it into the string when it is displayed on the page.

{% assign todays_date = 'November 26th' %}
{% assign app_settings = shop.metafields.app.settings %} // This metafield is the string "Hello! Today is {{ todays_date }} - thanks for shopping at my store."

Thinking it would be as simple as just displaying the app_settings variable now, I did just that:

<p>{{ app_settings }}</p

But alas… it didn’t work. It simply rendered the curly bracket variable reference in the string without trying to render the variable.

Hello! Today is {{ todays_date }} - thanks for shopping at my store.

After trying this strategy and variations of it for an hour or so, I realized it was never going to work. I asked around on various Shopify developer platforms and got some interesting responses, but basically the consensus was that it was not possible with Liquid.

I then stumbled across a reference to the Liquid filter “replace” - which I’ve used before but just for simple string replacement.

I figured I would give it a go - I was at wit’s end.

Attempt 2:

The metafield value is now simply:

‘Hello! Today is todays_date - thanks for shopping at my store.’

Obviously, this time there are no {{ curly brackets }} in the string.

Once again, I grabbed that metafield value after assigning the {{ todays_date }} variable.

{% assign todays_date = 'November 26th' %}
{% assign app_settings = shop.metafields.app.settings %} // This metafield is the string "Hello! Today is todays_date - thanks for shopping at my store."

This time, I used the Liquid filter function to replace the word ‘todays_date’ with the variable itself.

{% assign interpolated_app_settings = app_settings | replace: "todays_date", todays_date %}

Tada! It works perfectly.

The string renders as wished;

“Hello! Today is November 26th - thanks for shopping at my store”.

This sounds very simple, but it stumped me and a few other Shopify developers so I figured it may be helpful to someone else out there.

Cheers!