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}}
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With