0

In magento 1.9 i can get the page head description like this in phtml:

$this->getLayout()->getBlock('head')->getDescription()

How can i achieve this in Magento 2 ?

1 Answer 1

1

In magento2, if you want to get meta description at phtml then you have to call Magento\Framework\View\Page\Config.

As you want to use this value in phtml, then i suggest to use view model

Create View model class Description.php at Your module app/code/VendorName/Modulename/ViewModel and inject Config class and get description on phtml.

Example:

<?php
namespace StackExchange\SampleModule\ViewModel;

use Magento\Framework\View\Element\Block\ArgumentInterface;
use Magento\Framework\View\Page\Config;

class Description implements ArgumentInterface
{
    /**
     * @var Config
     */
    private $pageConfig;

    public function __construct(Config $pageConfig)
    {
        $this->pageConfig = $pageConfig;
    }
    public function getDescription()
    {
        return $this->pageConfig->getDescription();
    }
}

Assume that your phtml called at product detail page then and phtml called in layout as name "mycustom.block" and then create catalog_product_view.xml at app/code/VendorName/Modulename/view/frontend/layout

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceBlock name="mycustom.block">
                    <argument name="view_model_description" xsi:type="object">StackExchange\SampleModule\ViewModel\Description</argument>
                </arguments>

        </referenceBlock>
    </body>
</page>

Last step: access the view model class at your phtml file

<?php

/** @var $viewModelDescription \StackExchange\SampleModule\ViewModel\Description */

$viewModelDescription = $block->getViewModelDescription();

echo $viewModelDescription->getDescription();
?>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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