strings icon indicating copy to clipboard operation
strings copied to clipboard

Formatter feature request (text limit / word wrap)

Open mklemarczyk opened this issue 9 years ago • 10 comments

I do not have concept to implement this thing, but I think that it can be extension to asText formatter method.

First, there are a few methods of word wrapping:

  • Strict (as much as possible characters, can break the word)
  • Word rounded up (include last word that reach the limit)
  • Word rounded down (include last word before reach the limit)

I want use word wrapping to limit text. I know that I should use substr, but this method will break last word. There is also wordwrap, but first it does have third wrapping method, and secondly it only insert break line character.

This feature can be used in:

  • DataGrid columns and DetailView to display first few words of content,
  • Headers on page and page title, when it use some field that can be too long. (For example "question content" on "question update page",

mklemarczyk avatar May 17 '15 00:05 mklemarczyk

https://github.com/yiisoft/yii2/blob/master/framework/helpers/BaseStringHelper.php

lynicidn avatar May 17 '15 01:05 lynicidn

Thanks @lynicidn, but none method form this class cover my case. I used truncate for now, but it break last word.

mklemarczyk avatar May 17 '15 16:05 mklemarczyk

show how you use it

lynicidn avatar May 17 '15 16:05 lynicidn

Example:

$this->title = Yii::t('app', 'Update: {question}', [
    'question' => StringHelper::truncate($model->question, 20)
]);

In question is string: Do you like drink coffee at work? Function return string: Update: Do you like drink co... I expect string: Update: Do you like drink...

mklemarczyk avatar May 17 '15 17:05 mklemarczyk

https://github.com/yiisoft/yii2/blob/master/framework/helpers/BaseStringHelper.php#L128

lynicidn avatar May 17 '15 17:05 lynicidn

@lynicidn I do not know how many words should be printed. It depends on word lengths.

mklemarczyk avatar May 17 '15 17:05 mklemarczyk

@mklemarczyk ok, you right - i don't help for you - sorry.

simple way use truncate + find "white space of end" and apply endWith ('white space + partword + ...')

lynicidn avatar May 17 '15 17:05 lynicidn

Here is what you need. strrpos with negative limit finds last space in string before the limit.

    function truncate($string, $limit)
    {
        return substr($string, 0, strrpos($string, ' ', $limit - strlen($string)));
    }

    echo truncate('Do you like drink coffee at work?', 20);

Output is 'Do you like drink'

taxp avatar May 18 '15 07:05 taxp

StringHelper::truncateWords() is available since Yii 2.0.1

SilverFire avatar Aug 15 '17 20:08 SilverFire

as far as I understood the request it was to truncate words based on a maximum string length. StringHelper::truncateWords() is based on word count.

cebe avatar Aug 16 '17 15:08 cebe