Passing a parameter

Parameters assign values to variables at render time.

The assign and capture tags are helpful, but they’re static. Their values don’t change from render to render.

Parameters, on the other hand, assign values to variables each time you render a snippet. This allows you to use the same snippet to produce different output.

Input
<!-- /snippets/1/render?params={"color":"blue"} -->
<p>The sky is {{ color }}.</p>
Output
<p>The sky is blue.</p>

You can use the same snippet and a different parameter for a different output:

Input
<!-- /snippets/1/render?params={"color":"green"} -->
<p>The sky is {{ color }}.</p>
Output
<p>The sky is green.</p>

Array parameters are supported.

Input
<!-- /snippets/1/render?params={"names":["Jack","Nancy","Harry"]} -->
{% for name in names -%}
  Hi {{ name }}!
{% endfor -%}
Output
Hi Jack!
Hi Nancy!
Hi Harry!

Object parameters are also supported.

Input
<!-- /snippets/1/render?params={"person":{"name":{"first":"Jean-Luc","last":"Picard"}}} -->
Hi {{ person.name.first }}!
Output
Hi Jean-Luc!

Precedence

Given the various ways you can set variables, it’s important to consider precedence:

  1. The assign tag takes precedence over parameters.
  2. Parameters take precedence over the default filter.
  3. If a variable has no value via assign, parameters, or a default filter, it’s nil.
  4. If extra parameters are passed, they’re ignored.

For example:

Input
<!-- /snippets/1/render?params={"foo":"shirt","bar":"pants","corge":"socks"} -->
{% assign foo = "hat" -%}
{{ foo }}
{{ bar }}
{{ baz }}
{{ qux | default: "shoes" }}
Output
hat
pants

shoes
  • the value of foo was "hat", because, although foo was passed as a parameter, assign takes precedence;
  • the value of bar was passed by parameters;
  • the value of baz was neither assigned nor passed by parameter, so it’s value was nil and nothing was output;
  • the value of qux was neither assigned nor passed by parameter, but the default filter printed "shoes" to the page; and,
  • the parameter corge was passed but never used and ignored.