Using If Statement in PHTML in Magento 2.3 – Guide

magento2.3PHPphtml

Would like to put an if statement in the below code as follows.

If saleable qty <=0 (equals 0 or under), add CSS. Otherwise, add different CSS

<div class="left-stock">
    <strong>
        <?= ($block->salebleqty() != '') ? $block->escapeHtml(__('Only %1 left in stock!', $block->salebleqty())) : '' ?>
    </strong>
</div>

Best Answer

You can use the following code conditionally to display different CSS based on your condition:

<?= $block->salebleqty() <= 0 ? 'red' : 'green' ?>

For example:

<div class="left-stock">
    <?php if ($block->salebleqty() != ''): ?>
        <strong style="color:<?= $block->salebleqty() <= 0 ? 'red' : 'green' ?>">
            <?= $block->escapeHtml(__('Only %1 left in stock!', $block->salebleqty())); ?>
        </strong>
    <?php endif ?>
</div>

In this code, the color CSS property is added to the strong tag. You can adjust it to fit your needs.


For those using Magento 2.4.0 or higher version, it is recommended to use the $secureRenderer variable, which is available in the phtml template, to render the style tag. You can refer to the image_with_borders.phtml in Magento core for an example https://github.com/magento/magento2/blob/2.4.0/app/code/Magento/Catalog/view/frontend/templates/product/image_with_borders.phtml

Related Topic