Access variable in a section that’s defined in a snippet (up scoping)
This tip comes by way of a conversation in the Shopify Partner Slack between Edi and Lewis.
The question is, how do you access variables that are defined "below" your current scope, such as when a section defines a variable that you want to access in the section that included the snippet
Option 1 - Capture
Option 1 is to output the value from the snippet, and capture it in the section.
Example:
snippets/unique.liquid
﹛﹛ 'now' | date: '%N' ﹜﹜
sections/section-name.liquid
﹛% capture id %﹜
﹛% render 'unique' %﹜
﹛% endcapture %﹜
<div id="Section--﹛﹛id ﹜﹜"></div>
Option 2 - javascript
Option 2 is to use javascript to create a global variable in the snippet and then reference that same variable later in the section via js
Example:
snippet.liquid
﹛%- assign item_count = 0 -%﹜
﹛% for item in loop %﹜
﹛%- assign item_count = item_count | plus: 1 -%﹜
﹛% endfor %﹜
section.liquid
﹛% render 'unique' %﹜
<script>
const item_count = window.js_item_count
if (item_count === undefined || 0 ) {
...
} else {
...
}
</script>