'Limit the length of a post being displayed in handlebars
I have a blog app that I'm building for a class. It's an express app using sequelize and handlebars. I am able to display the most recent 4 plost on the home page and display all posts on the /post route, but I am trying to show only a limited number of characters with a read more.. buton that links to the full post. I cannot figure out how to limit the number of characters. I found some handlebars helpers on here but cannot get them to work.
Here is my partial:
<div class="container">
{{#each posts as |post|}}
<div class="card mt-4">
<div class="card-header bg-dark">
{{ post.title }}
<div class="text-end">Submitted {{ format_date post.createdAt}}</div>
</div>
<div class="card-body text-dark">
<h5 class="card-title">{{ User.username }}</h5>
<p class="card-text">{{ post.body }}</p>
<a href="/posts/{{ post.id}}" class="btn btn-dark">Read more...</a>
</div>
</div>
{{/each}}
</div>
I have a helpers.js file to format the date but I cannot figure out how to incorporate a helper to trim the post length.
Here is my current helper.js file:
function getMonthName(val){
switch(val){
case 0 :
return 'January';
case 1 :
return 'February';
case 2 :
return 'March';
case 3 :
return 'April';
case 4 :
return 'May';
case 5 :
return 'June';
case 6 :
return 'July';
case 7 :
return 'August';
case 8 :
return 'September';
case 9 :
return 'October';
case 10 :
return 'November';
case 11 :
return 'December';
default:
return '';
}
}
module.exports = {
format_date: date => {
var hours = date.getHours();
var minutes = date.getMinutes();
var ampm = hours >= 12 ? 'pm' : 'am';
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
minutes = minutes < 10 ? '0'+minutes : minutes;
var strTime = hours + ':' + minutes + ' ' + ampm;
let monthValue = date.getMonth();
return (getMonthName(monthValue)) + " " + date.getDate() + ", " + date.getFullYear() + " at " + strTime;
//return `${new Date(date).getMonth() + 1}/${new Date(date).getDate()}/${new Date(date).getFullYear()}`;
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
