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?
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:
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.