Cleaning code. snippet functionality.

Solved
Highlighted
New Member
3 0 1

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.

0 Likes
Highlighted
Shopify Partner
10 2 1

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'
} %}

 

Sam Webb
https://samthewebb.com
sam@samthewebb.com
0 Likes
Highlighted
New Member
3 0 1

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 

1 Like
Highlighted
Shopify Partner
10 2 1

No problem.

Sam Webb
https://samthewebb.com
sam@samthewebb.com
0 Likes