Question

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.

Was it helpful?

Solution

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 %}
Licensed under: CC-BY-SA with attribution
Not affiliated with drupal.stackexchange
scroll top