DumbDevGirl42069
DumbDevGirl42069

Reputation: 959

How can I pass classes in to a section in liquid / shopify?

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?

Upvotes: 0

Views: 2478

Answers (1)

drip
drip

Reputation: 12943

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:

test.section.liquid

The section file code:

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

Then you call the section this way:

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

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

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

Clarification

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 @dummy_class@ as well.

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

Upvotes: 1

Related Questions