How to truncate an HTML string cleanly on PrestaShop
Here is a little trick to bring back forgotten functions that have always been present in PrestaShop.
They are forgotten because PrestaShop doesn't integrate them in its code and so you have to remember that you have already used them to know that they exist.
Context
Sometimes we have to cut a text if it is too long because it is not always relevant where it is displayed.
To do this, like many, we use the Truncate function in Smarty.
{$name|truncate:25:'...'|escape:'html':'UTF-8'}
In this example we limit the length of the displayed text to 25 characters and add ... at the end.
This function is very practical but has two major problems.
- It does not handle accents very well and the calculation of the number of characters can be distorted
- She does not know how to work on an html text
The solution
For the first problem, you just have to encode in UTF-8 before using the Truncate function.
I'll let you experiment on an accented text the fact of passing escape before truncate, because this is not the purpose of my tip of the day.
Let's go back to the ultimate solution to limit the size of a full HTML text.
To find this forgotten function I went back to the code of version 1.6 where the description of the categories is limited to 350 characters and the rest of the text can be displayed simply by clicking on a button.
So in the corresponding TPL, I found that the short version of the description was directly from the controller.
So when I opened the corresponding controller, I found this code.
'description_short' => Tools::truncateString($this->category->description, 350),
So there is simply a truncateString() function to limit the length of a text in an html code.
The advantage of the Tools class
is that all its functions can be called from anywhere and even directly in a template file.
Typically, instead of displaying {$description_short}
you can treat the main variable as follows:
{Tools::truncateString($category->description, 350)}
the call of this function is made as follows:
public static function truncateString($text, $length = 120, $options = [])
- $text : the character string to be processed
- $length : the desired final length
- $options : an array of options to customize the output
- 'ellipsis' => '...',
- 'exact' => true,
- 'html' => true
This function comes from the CakePHP framework, I do not know if it was followed by the possible evolutions of CakePHP, but in any case it will save many designers for their next creations.
Conclusion
It is not always necessary to know the code by heart, but it is essential to know what you can do with it.
The competence of freelancers and developers on solutions like Prestashop is largely due to this accumulation of experience to respond without reinventing the wheel at the risk of breaking the basic functioning of PRestaShop and opening the door to updates or impossible maintenance.
Comments