First steps on coding stuff - quantity displayed on the product page

Hello everyone,

first of all I would like to say that I am really happy to see a community so active and so helpful.

Until now, I did not have the need to ask any question but it has been a couple of years following your suggestions.

It is time to ask you for a help, I have installed the Empire theme and I want to show on the product page the folowing info:

  1. If the product has the tag promo and qta >0:
    • if yes → display the text “just few items”
    • if not → do the check, if the quantity is >0 and <11
      • if yes → display the text "just X items left "
      • if not → black

I made it in the following way:

{% for tag in product.tags %} 
      {% for variant in product.variants %}
      		{% if tag == 'Promo' and variant.inventory_quantity > 0 %}  
     			 

 Only few left in stock!

      		{% elsif variant.inventory_quantity > 0 and variant.inventory_quantity < 11  %} 
  	  

 Only {{ variant.inventory_quantity }} left in stock!

      			{% endif %}
      {% endfor %}
     {% endfor %}

But I get https://ibb.co/Mp6XXmm

Can someone teach me how to fix it?

Thanks in advance.

1 Like

I think the 4 times the same text is caused by the fact I have more tags on that test product which creates a loop

I tried also in this way:

{% for tag in product.tags %} 
      {% for variant in product.variants %}
      		{% if collection.all_tags contains 'Promo' %}
      			{% if  variant.inventory_quantity > 0 %}  
     			 

 Only few left in stock!

      			{% endif %}
      		{% elsif variant.inventory_quantity > 0 and variant.inventory_quantity < 11 %}  
  	  

 Only {{ variant.inventory_quantity }} left in stock!

      			{% endif %}
      {% endfor %}
     {% endfor %}

Hi @Gesuelemi ,

I would suggest to detangle the logic and the presentation (display) by introducing some switches/local variables. My first idea was to rewrite your code as

{%- assign promo = false -%}
{%- assign lowstock = 9999 -%}
{%- assign lowstockMax = 11 -%}
{% for tag in product.tags %} 
      {% for variant in product.variants %}
               {% if variant.inventory_quantity > 0 %}
        		{% if tag == 'Promo'  %}  
       		     {%- assign promo = true -%}
       		{% endif %}     
       		{% if variant.inventory_quantity < lowstockMax   %} 
        		     {% assign lowstock = variant.inventory_quantity %}
        		{% endif %}     
      		{% endif %}    		  
      {% endfor %}
{% endfor %}     
{% if promo == true  %}  		  
     

 Only few left in stock!

{% elsif lowstock < lowstockMax  %} 
     

 Only {{ lowstock }} left in stock!

{% endif %}

Be aware that I have not tested it. Also, if you have more than one product variants, you can be sold out on one variant but not on others. So I would expect that there some additional cases apply.

Regards
Thomas

1 Like

Tewe thank you very much! you are … My hero of the day!!!