0

Building a D8 Commerce site and trying to hide the price if the product is out of stock. I can access the stock value with this:

{{ product.variation_field_stock_level.0 }}

I've tried this:

{% if product.variation_field_stock_level.0 > 0 %}
 {{ product.variation_price }}
{% else %}
 <p>Sold</p>
{% endif %}

...but it prints the price regardless of whether the stock value is 0 or 1 (or more). I've also tried:

{% if product.variation_field_stock_level.0 == 0 %}
  <p>Sold</p>
{% else %}
  {{ product.variation_price }}
{% endif %}

Regardless of what I try it just will not work.

2
  • What template file are you using? Are you sure the template file is being read? – No Sssweat Nov 18 '20 at 15:05
  • I'm using the standard commerce product template commerce-product.html.twig I can see the value for the stock level printed on the front end, but the template won't do that calculations – Robert Rhead Nov 18 '20 at 15:13
3

This is very close - but it seems you are missing the actual stock level value from the object. Start by doing something like:

{{product.variation_field_stock_level.0|json_encode}}

Run it through a json cleaner to make it readable, like: JSON Cleaner

You will see this:

{"#type":"html_tag","#tag":"p","#value":0}

Now the conditional will be:

{% if product.variation_field_stock_level.0['#value'] > 0 %}
    {{ product.variation_price }}
{% else %}
    <p>Sold</p>
{% endif %}
3
  • 3
    I would also recommend writing this logic inside of a preprocess function instead of TWIG. The question was specifically how to do this in TWIG - so the answer reflects that. – erier Nov 18 '20 at 15:39
  • 1
    You're correct. With the additional |json_encode I got this: {"#type":"html_tag","#tag":"p","#value":0} So the answer is to use {{ product.variation_field_stock_level.0['#value'] }} – Robert Rhead Nov 18 '20 at 15:44
  • Awesome! I'll update the answer to reflect the [#value] bit. – erier Nov 18 '20 at 15:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.