In my store I offer free samples. I want to swap the sample image, with the variant image of the product selected.
<tbody class="line-item-table__list">
{% assign num_samples = 0 %}
{%- for line_item in cart.items -%}
{% assign free_sample_product = all_products[settings.free_sample_product] %}
{% assign free_sample_variant_id = free_sample_product.selected_or_first_available_variant.id %}
{% if line_item.variant.id == free_sample_variant_id %}
{% assign num_samples = num_samples | plus: line_item.quantity %}
// Here is where I would like to swap the images
{% assign line_item.image = //this will not work// free_sample_variant.image%}
{% endif %}
I need to reference the variant image, but I am not sure how to reference it recursively. Any help would be appreciated.
all_products can only be use ~20 times per page, use it OUTSIDE of the forloop since no data from inside the forloop is required to get the product.
if your setting a variant just use first_available_variant the selected version only applies if using url parameters such as with ajax/fetch in javascript.
You can’t override a liquid objects properties
{% assign line_item.image = //this will not work// free_sample_variant.image%}
Make your own variable logic to replace any line_item.image
This does not account for putting the image into an tag or other html.
{% liquid # free samples vars
assign num_samples = 0
assign free_sample_product = all_products[settings.free_sample_product]
#assumes first available variant is always the correct variant
assign free_sample_variant_id = free_sample_product.first_available_variant.id
assign custom_line_item_image = free_sample_variant.image
%}
{%- for line_item in cart.items -%}
{% liquid
if line_item.variant.id == free_sample_variant_id
assign num_samples = num_samples | plus: line_item.quantity
# variable to swap the images
# !!! use boolean logic to replace any line_item.image references in this loops context
assign use_custom_image = true
else
assign use_custom_image = false
endif
%}
...
{% if use_custom_image %}{{ custom_line_item_image }}{% else %}{{ line_item.image }}{% endif %}
...
{% endfor %}