Custom Liquid Filter: "wrap_if"

  • Liquid
 0  Votes for this feature
Request for a custom liquid filter that appends/prepends strings (or variables) only if the target object is not null or empty. This will be useful when we have properties/values we want to conditionally output within it's own HTML structure only when it is present (which is a common task).
For example, in Menu layouts we only want to render a class value (and it's surrounding attribute) if it exists. Currently we do it like this: {% if item.itemClass != null and item.itemClass != "" %}class="{{item.itemClass}}"{% endif %} Which is a lot of code to do a simple thing.

The idea for a custom liquid filter to achieve the same thing in a cleaner way would be like this:
TEMPLATE: {{  | wrap_if: '', ''}}
EXAMPLE: {{item.itemClass | wrap_if: 'class="', ‘"'}}


So behind the scenes, "wrap_if" does the same as {% if item.itemClass != null and item.itemClass != "" %}