Is there a way to include code in a metafield that can be used as liquid instructions?
For example:
add a collection metafield (collection.metafields.custom.variant_collection_rule)
add a value to the metafield (variant.title contains ‘Blue’)
use that in my templat so that {%- if collection.metafields.custom.variant_collection_rule -%} would be interpreted as {%- if variant.title contains ‘Blue’ -%}
If that’s not possible, I welcome any alternate suggestion that doesn’t involve creating a new template for each condition.
I am making a collection that includes specific product variants (in this example, only blue variants).
I added a template that pulls all products that include the variant and outputs all the variants of those products. Then I filter the variants so only the blue variants are displayed.
It works well when I hard-code {%- if variant.title contains ‘Blue’ -%} in the loop.
Now I want to make the code reuseable so that I can target other conditions (variant titles or variant metafields).
{% for product in collection.products %}
{% for variant in product.variants %}
{% if variant.title contains 'Blue' %}
{%
render 'product-variant-item' with
prod: product,
var: variant,
product_columns: section.settings.columns,
aspect_ratio: settings.product_listing_aspect_ratio,
has_grid_reveal: true
%}
{% endif %}
{% endfor %}
{% endfor %}
Thanks. As I was going to sleep, I came up with a similar solution. Writing out the exact problem helped.
Add 3 metafields:
collection metafield: variant_type (‘title’ or ‘metafield’)
collection metafield: variant_value (string - value to be searched)
variant metafield: variant_collection (string - value of collection to be included in - set “use in automated collection”!)
{% for product in collection.products %}
{% for variant in product.variants %}
{% case collection.metafields.custom.variant_type %}
{% when 'title' %}
{% if variant.title contains collection.metafields.custom.variant_value %}
{%
render 'product-variant-item' with
prod: product,
var: variant,
product_columns: section.settings.columns,
aspect_ratio: settings.product_listing_aspect_ratio,
has_grid_reveal: true
%}
{% endif %}
{% when 'metafield' %}
{% if variant.metafields.custom.variant_collection contains collection.metafields.custom.variant_value %}
{%
render 'product-variant-item' with
prod: product,
var: variant,
product_columns: section.settings.columns,
aspect_ratio: settings.product_listing_aspect_ratio,
has_grid_reveal: true
%}
{% endif %}
{% endcase %}
{% endfor %}
{% endfor %}