Search code examples
ember.jsember-cli

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}}


Solution

  • 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