Personalized checkout and custom promotions with Shopify Scripts
While I am cleaning code for a website. There is a LOT of redundent code. I know snippets have access to variables in their parent functions. But can I reference a singular variable from a snippet? Ideally, I would want to create something like a "library" that you have in other languages.
Solved! Go to the solution
This is an accepted solution.
No, this is not a feature of Liquid (within Shopify). Liquid does not have the concept of user defined functions nor objects, which are the 2 things you'd need to create a namespace contained "library".
That being said, if you're really dedicated you could create a snippet that takes some arguments and utilizes a case statement to render out other snippets to somewhat mimic the above pattern. Here's a simple example, but you could do this on a much more complex and complicated level:
string.liquid
{% comment %}
Args:
- method
- text
{% endcomment %}
{% liquid
case method
when 'reverse'
render 'string-reverse', text: text
when 'uppercase'
render 'string-uppercase', text: text
else
echo text
%}
And then in say 'string-uppercase.liquid' you have the code:
{% comment %}
Args:
text
{% endcomment %}
{% liquid
assign upcase_text = text | upcase
echo upcase_text
%}
And you would call it like:
{% render 'string' with {
method: 'uppercase',
text: 'hello world'
} %}
This is an accepted solution.
No, this is not a feature of Liquid (within Shopify). Liquid does not have the concept of user defined functions nor objects, which are the 2 things you'd need to create a namespace contained "library".
That being said, if you're really dedicated you could create a snippet that takes some arguments and utilizes a case statement to render out other snippets to somewhat mimic the above pattern. Here's a simple example, but you could do this on a much more complex and complicated level:
string.liquid
{% comment %}
Args:
- method
- text
{% endcomment %}
{% liquid
case method
when 'reverse'
render 'string-reverse', text: text
when 'uppercase'
render 'string-uppercase', text: text
else
echo text
%}
And then in say 'string-uppercase.liquid' you have the code:
{% comment %}
Args:
text
{% endcomment %}
{% liquid
assign upcase_text = text | upcase
echo upcase_text
%}
And you would call it like:
{% render 'string' with {
method: 'uppercase',
text: 'hello world'
} %}
Thanks,
That is pretty much what I was thinking. Shopify documentation is a mess in my opinion so I wanted to make sure I did not miss something super obvious. Thank you
No problem.
Learn how to expand your operations internationally with Shopify Academy’s learning path...
By Shopify Feb 4, 2025Hey Community, happy February! Looking back to January, we kicked off the year with 8....
By JasonH Feb 3, 2025Expand into selling wholesale with Shopify Academy’s learning path, B2B on Shopify: Lau...
By Shopify Jan 28, 2025