Vincent Cfn
Vincent Cfn

Reputation: 97

Express JS : Handlebars "each" tag not displaying content

I'm using Express JS and Handlebars package, and I'm actually facing something weird. I don't know if I missed something, I hope so, but I can't figure out what's wrong in my code.

I'm using : https://github.com/ericf/express-handlebars

I can't make a {{#each}} statement work in my code.

Here is what I have:

views.ts

const Views = {
    config: {
        // views template configuration
        extname: '.hbs',
        helpers: {
            modulesList: () => {
                return appModules.modulesList();
            },
            foo: () => { return 'FOO!'; },
            bar: ['tic', 'tac', 'toe'],
            // bar: () => { return ['tic', 'tac', 'toe'] },
        }
    },
}

// Views is exported

app.ts

const exphbs  = require('express-handlebars');
const views = require('twiice/views.ts');

app.engine('.hbs', exphbs(views.config));
app.set('view engine', '.hbs');
app.set('views', './twiice/views');

home.hbs

<div class="col">
    {{#each bar}}
       <h6 class="text-light text-uppercase ls-1 mb-1">{{foo}}</h6>
    {{/each}}
    <h6 class="text-light text-uppercase ls-1 mb-1">Overview</h6>
    <h5 class="h3 text-white mb-0">Sales value</h5>
    <h6 class="text-light text-uppercase ls-1 mb-1">{{foo}}</h6>
</div>

Actually, foo is displayed on the last h6 in the html code, which means the helper is loaded.

But the each statement is not displaying anything for bar.

Following the doc: https://handlebarsjs.com/guide/builtin-helpers.html

I can't see anything wrong :/

Thanks a lot for your help, I'm still learning! :)

Complete code here: https://github.com/Brawcks/twiice-ts/

Upvotes: 0

Views: 560

Answers (1)

76484
76484

Reputation: 8993

You are not using the bar helper correctly.

Handlebars helpers are functions. When you want to use a helper in your template, you use it in a Handlebars expression, like {{uppercase firstName}}. In this expression, uppercase is the identifier of a helper we defined and firstName is a variable in our data context Object that will be passed to our uppercase helper.

The expression {{#each bar}} is telling handlebars to invoke the built-in #each block helper on the variable bar in the data context Object.

However, bar does not exist in the data context Object because bar is not a part of our data, but a different helper that we have defined. So our problem is: How do we call two helpers within the same Handlebars expression?

Handlebars has an answer for this question; it is Sub-expressions. All it requires is for you to wrap your inner expression(s) in parentheses.

This means that updating your code to {{#each (bar)}} will be sufficient to tell Handlebars that bar is a helper that we want to invoke and whose return value we want to pass to #each.

I have created a fiddle for your reference.

Upvotes: 1

Related Questions