I am using liquid templates and I'm trying to figure out a way to render a template with an optional variable allowed to be passed.

In this case, I want the template to load with an image background if one is passed, and if none is passed then have it display a solid color background.

In something like Vue, you can set a property to have a default value that is used if one is not passed, is this possible in Liquid?

here's an example of how I want it to work (but this doesn't work):

example.liquid

{% assign property = "Default value text" %}

{{ property }}

then:

index.liquid

{% render 'example.liquid', property: "Some Other Text" %}

would render:

Some Other Text

But if you instead do:

index.liquid

{% render 'example.liquid' %}

would render:

Default value text

So is there any way to basically have a passed value from a render tag override an assigned property? Or maybe assign a property in a way where it listens for an assigned value, and if one does not get passed, to display the default instead?

2

There are 2 best solutions below

0
Bais On

I solve setting deafault values by wrapping the assignment in an unless-Block (docs), which becomes true if property is False (None or the empty value resolves to a falsy value in python).

Therefore, your sample code would look like:

{% unless property%}
  {% assign property = "default value" %}
{% endunless %}

{{ property }}

Then depending on whether or not you pass the variable the default will be set. However, there is a corner case: If you try to pass False, it will not work as the default would be set.

0
John Lewis On

Your method of passing the parameter is correct, but you can also set a default parameter in the assign within.

Also worth mentioning you don't use the liquid extension on the render: So in index.liquid, snippets/example.liquid would be called as such:

{% render 'example', property: 'some other text' %}

Then in your snippet, you can set the variable as the one passed in with a default:

{% assign property = property | default: 'Default value text' %}
{{ property }}

This will use the passed value if it exists, or default to "Default Value Text" if it isn't passed in.