Magento 2.2.5 – Widget/Block Code in Product Custom Attribute Not Rendering

blockscustom-attributesmagento2product-attributewidget

I have created custom attribute of Input Type "Text Area" with WYSIWYG option Enable.

enter image description here

After that add widget code in that product custom attribute input at store back-end.

enter image description here

Its showing same code instead of widget value at store front-end product detail page.
enter image description here

Code in template file.

<?php
$_product = $block->getProduct();
echo $_product->getTest();

Please guide me, why widget/block code not rendering at front-end ?

Best Answer

Yes it will return same data as that data needs to be filter to get actual html. It's kind of same data as cms page or block have all textarea type attribute data needs to be filter to get actual rendered value.

So do one thing in layout, pass viewmodel argument inside your block for which you have that template. Like this:

<arguments> <argument name="viewModel" xsi:type="object">Namespace\ModuleName\ViewModel\Product</argument> </arguments>

Create a class as specified in view model argument and inside class you need to use :

use Magento\Cms\Model\Template\FilterProvider;

Then declare it in constructor

And create a function to call from template and inside function use it like:

$this->filterProvider->getPageFilter()->filter($_product->getTest());

Then you can call your viewModel inside template like this:

$viewModel = $block->getViewModel();

And call your function from $viewModel.

For detail about viewModel you can check here

You can create an helper and call it directly from template same thing (as stated above for class) can be used in helper class as well.

Related Topic