Using If Statement in PHTML in Magento 2.3 – Guide


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">
        <?= ($block->salebleqty() != '') ? $block->escapeHtml(__('Only %1 left in stock!', $block->salebleqty())) : '' ?>

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())); ?>
    <?php endif ?>

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

Related Topic