ClickCease

Transferring Variables from Templates to Sections in Shopify

Transferring Variables from Templates to Sections in Shopify

When building Shopify themes, it is often necessary to pass data between templates, snippets, and sections to enable dynamic functionality.

For snippets, you can easily achieve this by first declaring your variable,

{% assign string = 'Hello world' %}


and then calling the snippet passing in the variable we just created.

{% render 'snippet.liquid', text: string %}


Snippets can access variable templates so we can then access our variable inside the snippet.

{{ text }}


As a side note, the 
 include tag is deprecated; moving forward, use the render tag instead.

While this works great for snippets, what about sections? The bad news is that, because of how the section scope works in Shopify, this is not possible. Sections are self-contained modules that operate only within their own scope; unfortunately, they cannot access variables declared in templates. Nor is it possible to pass variables to them when they are invoked, like you can with snippets. Shopify developers, if you are reading this: we would be eternally grateful if you could add this feature in a future release!

In light of this limitation, is there anything else we can do? As with a lot of things in Shopify, there is what I would call a “dirty hack” that can overcome this limitation to some extent, but it’s only a partial solution and unfortunately doesn't fully solve the problem.

First, we create a section which we will call section.liquid and inside it we place an assigned placeholder like this

[placeholder]


Then inside our main template, the trick is to use the 
replace string filter to switch that placeholder text with some content like this

{% assign string = 'Hello world' %}
{% capture text %}
  {% section 'section' %}
{% endcapture %}
{{ text | replace: '[placeholder]', string }}


What happens here is that we use the 
capture tag to assign the contents of the whole section to the variable text, and then we use the replace filter to update the placeholder with the text we want to display.

This is a useful trick to have up your sleeve to get around the fact that you can’t pass the variable directly to the section. The caveat is that you can only replace content after the section is rendered. You unfortunately can’t do any further processing on the placeholder text within the section itself. Ultimately, this trick can only be used for content generated within the template, not in the section. This is a downside, as it would be extremely useful to use a placeholder variable within the section, which the section could then process internally. 

Watch this space for any developments on this, as it is a part of Shopify that we are constantly trying to leverage for creative solutions, and as the platform evolves, so will our techniques.