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.
By investing 30 minutes of your time, you can unlock the potential for increased sales,...
By Jacqui Sep 11, 2024We appreciate the diverse ways you participate in and engage with the Shopify Communi...
By JasonH Sep 9, 2024Thanks to everyone who participated in our AMA with 2H Media: Marketing Your Shopify St...
By Jacqui Sep 6, 2024