1

I am using 2.3.1

I have truncated product name in the listing page and displayed dots if the length of the name is more than 27 but the problem is that there are special characters like &,'," etc. in the product name. So, I used html_entity_decode function to properly decode all special character. it is working fine for some cases

Now I have another scenario where the product name is having double quote two times in a consistent position. So, when I tried to truncate the product name the first double quote is displayed properly but the second one is not decoded properly.

Product Name: 18inch woodproduct""Iron Box

I have used the below code:

<a class="" href="<?= /* @escapeNotVerified */ $_product->getProductUrl() ?>">
   <?php 
     $product_name = $_product->getName();
     //$string = strval($product_name); 
     $len = strlen($product_name); 
     if($len > 27) {
        echo html_entity_decode(substr($product_name,0,27),ENT_QUOTES).'...';    
      } else {
        echo $product_name;
      }
    ?>
</a>

result in the front end listing page: 18inch woodproduct"&qu

How can I solve this issue?

3
0

In summary I think you can use

Magento\Framework\Filter\FilterManager $filter

$filter = $this->filter

$this->filter->truncate($product_name, ['length' => 27, 'etc' => '...', 'remainder' => $remainder])

Here is an example:

https://github.com/magento/magento2/blob/6ea7d2d85cded3fa0fbcf4e7aa0dcd4edbf568a6/app/code/Magento/Sales/Block/Order/Item/Renderer/DefaultRenderer.php#L168

In response to your question you could create a String.php helper with the above logic and then you can use it in a template like this

String.php

public function truncate($product_name) {
    return $this->filter->truncate($product_name, ['length' => 27, 'etc' => '...', 'remainder' => $remainder]);
}

Template

$helper = $this->helper('\Xigen\Data\Helper\String');
echo $helper->truncate($product_name)

No you don't have to use remainder.

3
  • Is it necessary to add "remainder"? and my other question is that how can I use your code in .phtml file? May 25 '19 at 10:06
  • Updated answer in response to second question May 25 '19 at 21:16
  • I have implemented your solution but still no luck May 27 '19 at 4:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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