Ember 2: crop text and add ellipses

I am looking for a simple addon or helper for long lines that will truncate, as well as add ellipses. I found some examples with the handlebar helper, but I think most of them are deprecated. I created an ember helper called truncate-text and tried to combine the examples, but was unsuccessful. In addition, if there is a way to determine the limit in the number of characters for each use case, it will be a bonus.

Here's 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 .hbs template {{truncate-text text="Long text here."}

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

+4
source share
2 answers

:

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);

,

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

https://ember-twiddle.com/fcb02795216a206b64dc

+9

javascript, css

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

JSbin

+1

Source: https://habr.com/ru/post/1619264/


All Articles