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 >
{{#each posts as |post|}}
<div >
<div >
{{ post.title }}
<div >Submitted {{ format_date post.createdAt}}</div>
</div>
<div >
<h5 >{{ User.username }}</h5>
<p >{{ post.body }}</p>
<a href="/posts/{{ post.id}}" >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()}`;
}
}
CodePudding user response:
I found a bunch of complicated handlebars helpers but I figured out a simple solution.
In the helps file I just added:
post_tease: str => {
const first25 = str.slice(0, 50);
return first25;
}
Then in the post I just added {{ post_tease post.body }}
