Only one Handlebar Helper works at a time. Either stripTags or truncate, not both?

Viewed 289

I'm trying to use two Handlebar Helpers on the {{body}} but only one of them is working? I'm following Traversy media's Node.js App from Scratch youtube course here https://youtu.be/SBvmnHTQIPY at 1:44:10. I triple checked my code against his using diffchecker. Here are the two helpers I'm using on the template index.hbs:

<p>{{stripTags (truncate body 150)}}</p>

But, once I add "150" to truncate, the helper 'stripTags' stops working and shows the html but does truncate it to 150 characters. from this:

J Story 2 I'm baby marfa coloring book church-key, vape leggings 8-bit hashtag umami tbh mixtape chillwave. Butcher cliche unicorn, yr VHS bicycle rights try-hard drinking vinegar. Woke vaporware art party subway tile. Small batch celiac kombucha readymade, chia ramps hoodie artisan banjo kale chips. Austin semiotics wayfarers pinterest, four dollar toast gochujang humblebrag leggings.Offal 8-bit sustainable skateboard quinoa.

to this:

J Story 2 <p style="box-sizing: inherit; margin-bottom: 1.5em; color: rgb(4, 4, 2); font-family: "Helvetica Neue", Helvetica, Arial, Frutiger,...

Handlebar Helper code:

const moment = require('moment')

module.exports = {
    formatDate: function (date, format) {
        return moment(date).utc().format(format)
    },
    truncate: function (str, len) {
        if (str.length > len && str.length > 0) {
            let new_str = str + ' '
            new_str = str.substr(0, len)
            new_str = str.substr(0, new_str.lastIndexOf(' '))
            new_str = new_str.length > 0 ? new_str : str.substr(0, len)
            return new_str + '...'
        }
        return str
    },
    stripTags: function (input) {
        return input.replace(/<(?:.|\n)*?>/gm, '')
    },
}

App.js

const path = require('path')
const express = require('express')
const mongoose = require('mongoose')
const dotenv = require('dotenv')
const morgan = require('morgan')
const exphbs = require('express-handlebars') 
const passport = require('passport')
const session = require('express-session')
const MongoStore = require('connect-mongo')(session)
const connectDB = require('./config/db')

//Load config
dotenv.config({path: './config/config.env' })

// Passport config
require('./config/passport')(passport)

connectDB()

const app = express()

//Body parser
app.use(express.urlencoded({ extended: false }))
app.use(express.json())

// Logging
if(process.env.NODE_ENV === 'development') {
    app.use(morgan('dev'))
}

// Handlebars Helpers
const { formatDate, stripTags, truncate, } = require('./helpers/hbs')

// Handlebars
app.engine('.hbs', exphbs({ 
    helpers: {
        formatDate,
        stripTags,
        truncate,
    },
    defaultLayout: 'main', 
    extname: '.hbs',
    })
)
app.set('view engine', '.hbs')
2 Answers

Currently going through the exact Tutorial & I had this problem.

After playing around with the code, I noticed that the problem is solved by changing the order in which the functions or helpers where called.

That is instead of

<p>{{stripTags (truncate body 150)}}</p>

I used

<p>{{truncate (stripTags body) 100}}</p>

Why does this work??

I dont know per se, i am not an expert on Regex and just learing JS. I did notice however that the regex used by brad expects to see the tags <> but when truncate is called first. It might have truncated the '>' in some instances. So first calling the stripTags helper function before calling truncate was the soution for me

So I fixed a typo in the add story template, I misspelled 'id', but when I fixed it the problem still did not go away! I moved a few commas around, fixed some other typos that didn't seem to affect the page. BUT when I moved 'stripTags' within the parentheses and 'truncate' outside of the parentheses, it suddenly worked! Why is it working now? smh.

Fixed code from the Stories Index page:

<h1>Stories</h1>
<div class="row">
    {{#each stories}}
    <div class="col s12 m4">
        <div class="card">
            <div class="card-image">
                {{!-- todo: editIcon --}}
            </div>
            <div class="card-content center-align">
                <h5>{{title}}</h5>
                <p>{{truncate (stripTags body) 200}}</p>
                <br>
                <div class="chip">
                    <img src="{{user.image}}" alt="">
                    <a href="/stories/user/{{user._id}}">{{user.displayName}}</a>
                </div>
            </div>
            <div class="card-action center-align">
                <a href="/stories/{{_id}}" class="btn grey">Read More</a>
            </div>
        </div>
    </div>
    {{else}}
        <p>No Stories To Display</p>
    {{/each}}
</div>
Related