I've migrated Magento 1 to Magento 2, In the Magento 1 site on product listing page I've truncated the length of the short description.

e.g- echo Mage::helper('core/string')->truncate($short_description, '120');

I require the same thing in Magento 2 way, how can I achieve it?

Note:- I don't want to use simple core PHP to restrict length.

  • Check my below solution and let me know if working or not. – Suresh Chikani Jul 19 '18 at 11:37

You can truncate string in Magento-2 by below code

Inject below parameters to your class __construct

protected $filter;

public function __construct(
        \Magento\Framework\Filter\FilterManager $filter
    ) {
        $this->filter = $filter;

You can truncate string by below code

$this->filter->truncate($short_description, ['length' => 120]));
  • Sorry! I was engaged on some other urgent works so looked on this late.thanks for the reply.i tried but it didn't work in the class "Magento\Catalog\Block\Product\ListProduct". – wakar Ahamad Jul 24 '18 at 12:27
  • any error or not working? – Suresh Chikani Jul 24 '18 at 12:29
  • Getting errors, so i tried helper way & it works. – wakar Ahamad Jul 24 '18 at 12:42
  • I've used cache:clean. when we need to delete generated? i used the same using helper but it works without deleting generated why? – wakar Ahamad Jul 24 '18 at 12:48
  • keep in mind if you add any constructor argument, It required delete generated folder. if you clean just cache it will be not working and throw error. – Suresh Chikani Jul 24 '18 at 12:49

After spending two hours approx I've done this by using a helper.

Helper Path:-

Magento\Catalog\Helper\Product\ProductList.php(I'll be overriding later so you can also).

Added Following code:-

    // Extends class \Magento\Framework\App\Helper\AbstractHelper

class ProductList extends \Magento\Framework\App\Helper\AbstractHelper
     public function __construct(
            \Magento\Framework\Filter\FilterManager $filter
          ) {
              $this->filter = $filter;
                // My custom method
         public function truncateString($value, $length = 80)
                return $this->filter->truncate($value, ['length' => $length]) ;

// In the template file, just called custom method:-


Note:- I tried to do it using block but due to the time restriction i'm not able will try later. if anyone do the same via block then please share here.

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.