【问题标题】:Limit the length of a post being displayed in handlebars限制在车把中显示的帖子的长度
【发布时间】:2022-02-08 07:56:22
【问题描述】:

我有一个正在为班级构建的博客应用程序。这是一个使用 sequelize 和车把的快速应用程序。我能够在主页上显示最近的 4 个 plost 并在 /post 路由上显示所有帖子,但我试图仅显示有限数量的字符,并带有 read more.. 链接到完整帖子的按钮。我不知道如何限制字符数。我在这里找到了一些车把助手,但无法让它们工作。

这是我的部分:

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

我有一个 helpers.js 文件来格式化日期,但我不知道如何合并帮助器来修剪帖子长度。

这是我当前的 helper.js 文件:

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()}`;
    }
}

【问题讨论】:

  • 您的问题似乎与 Sequelize 无关。请删除此标签
  • 你试过创建这样的助手吗?
  • 我做过,但不知道怎么写。我在这里找到了一个把手。注册....但我不知道如何使用它。我把它放在助手文件中,它没有用。我不知道该放在哪里。
  • 我认为您应该分享您的尝试,其他人可以帮助您纠正路线。

标签: express handlebars.js


【解决方案1】:

我找到了一堆复杂的车把助手,但我想出了一个简单的解决方案。

在我刚刚添加的帮助文件中:

post_tease: str => {
    const first25 =  str.slice(0, 50);
    return first25;
}

然后我刚刚在帖子中添加了 {{ post_tease post.body }}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-27
    • 2022-07-12
    • 2021-05-18
    • 1970-01-01
    相关资源
    最近更新 更多