How Can I Pass Classes In To A Section In Liquid / Shopify?

- 1 answer

For example passing in a snippet

{% include 'icon-top', classes:'back-to-top__icon' %} I can pass the class back-to-top__icon into icon-top snippet <svg class="icon {{ classes }}" somesvg stuff here ></svg>

Doing the same with a section doesn't work - is there any way to do this in liquid?



Sections doesn't accept anything outside of the section file. You can look the section like a closed platform nothing comes inside or outside of the section.

The means that variables created outside/inside the section are not accessible inside/outside of it.

That said you can hack it slightly to achieve what you want.

For example:

The section file:


The section file code:

<div class="{{dummy_class}}"></div>

Then you call the section this way:

<div style="display: none;">
  {% section 'test.section' %}

{% capture section_capture %}
  {% section 'test.section' %}
{% endcapture %}

{{ section_capture | replace: '{{dummy_class}}', 'back-to-top__icon' }}


You might be asking why are we calling the section two times?

When we call the section in a {% capture %} tag it's not shown in the admin panel that's why are showing it in a hidden div only to show it in the admin and we don't do anything else with it.

After that we capture the section in a variable section_capture, this will return the content of section and we can replace anything we want in there.

That's why we added this {{dummy_class}} dummy variable. It's wrapped in liquid but you can treat it as text and not liquid, so we can write it like so @[email protected] as well.

After that we just target that string and replace it {{ section_capture | replace: '{{dummy_class}}', 'back-to-top__icon' }}