Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ember 2: Truncate text and add ellipses

I'm looking for a simple addon or helper for long strings that would truncate and also add ellipses. I found some examples with handlebar helper but I think most are outdated. I created an ember helper called truncate-text and tried to piece together examples, but is unsuccessful. Also, if there's a way to define a limit in number of character per use cases, that would be a bonus.

Here is what I have in my helpers/truncate-text.js import Ember from 'ember';

export function truncateText(text) {
  if (text.length > 60) {
    var theString = text.substring(0, 60) + " ... ";
    return new Ember.Handlebars.SafeString(theString);
  } else {
    return text;
  }
}

export default Ember.Helper.helper(truncateText);

In my template.hbs {{truncate-text text="Long text here."}

Would be grateful if I can do this {{truncate-text text="Long text here." limit=65}}

like image 719
user1917032 Avatar asked Dec 09 '15 21:12

user1917032


2 Answers

Here is an example of a helper to truncate the text based on the limit you specify:

function truncateText(params, hash) {
  const [ value ] = params;
  const { limit } = hash;
  let text = '';

  if (value != null && value.length > 0) {
    text = value.substr(0, limit);

    if (value.length > limit) {
      text += '...';
    }
  }

  return text;
}

export default Ember.Helper.helper(truncateText);

And then you would use it in templates as following

{{truncate-text "Lorem ipsum dolor long text" limit=5}}

You can see demo here https://ember-twiddle.com/fcb02795216a206b64dc

like image 116
Altrim Avatar answered Oct 15 '22 15:10

Altrim


usually you don't need javascript for it, you can use css instead

.text {
  overflow: hidden;
  text-overflow: ellipsis;
  width: 100px;
  background: green;
  white-space: pre;
}

JSbin

like image 1
Bek Avatar answered Oct 15 '22 16:10

Bek