How to display labels within custom theme
Some themes have different layouts that display products in their own unique formats. In this case, you need to adjust templates manually. Take a look at the real example below.
Assuming that $_product
contains a current product object, you will need to insert the following code to make our extension place positioned Labels.
<?php
echo $block->getLayout()
->createBlock('\Mirasvit\CatalogLabel\Block\Product\Label\Renderer')
->setProduct($_product)
->setType(view_type)
->toHtml();
?>
Where view_type should be list
or view
correspondingly to where this code is placed.
Real example adding label in the custom theme
Consider the standard template Magento/Catalog/view/frontend/templates/product/list.phtml, which contains the following code:
<?php foreach ($_productCollection as $_product): ?>
<?php /* @escapeNotVerified */ echo($iterator++ == 1) ? '<li class="item product product-item">' : '</li><li class="item product product-item">' ?>
<div class="product-item-info" data-container="product-grid">
<?php
$productImage = $block->getImage($_product, $image);
if ($pos != null) {
$position = ' style="left:' . $productImage->getWidth() . 'px;'
. 'top:' . $productImage->getHeight() . 'px;"';
}
?>
<?php // Product Image ?>
<a href="<?php /* @escapeNotVerified */ echo $_product->getProductUrl() ?>" class="product photo product-item-photo" tabindex="-1">
<?php echo $productImage->toHtml(); ?>
</a>
<div class="product details product-item-details">
...
<?php endforeach; ?>
We will insert our label overlay code right before the closing anchor tag <\a>
which is a wrapper for product image:
<?php foreach ($_productCollection as $_product): ?>
<?php /* @escapeNotVerified */ echo($iterator++ == 1) ? '<li class="item product product-item">' : '</li><li class="item product product-item">' ?>
<div class="product-item-info" data-container="product-grid">
<?php
$productImage = $block->getImage($_product, $image);
if ($pos != null) {
$position = ' style="left:' . $productImage->getWidth() . 'px;'
. 'top:' . $productImage->getHeight() . 'px;"';
}
?>
<?php // Product Image ?>
<a href="<?php /* @escapeNotVerified */ echo $_product->getProductUrl() ?>" class="product photo product-item-photo" tabindex="-1">
<?php echo $productImage->toHtml(); ?>
<!-- Labels code for custom themes -->
<?php
echo $block->getLayout()
->createBlock('\Mirasvit\CatalogLabel\Block\Product\Label\Renderer')
->setProduct($_product)
->setType('list')
->toHtml();
?>
</a>
<div class="product details product-item-details">
...
<?php endforeach; ?>
This code will create a block which will overlap the image, creating a place for our label.
The same approach can be applied to other Magento 2 custom themes.