1

I use express-handlebars with Node JS and I am trying to display informations from the array games on my HTML page using #each. But handlebars won't display the values inside my object. Even if it is not a nested object.

But if I only write {{this}}, it displays all the object like if it was a string. And if I do {{this.time}}, nothing is displayed.

I'm using Node JS v14.18.1, express v4.17.2 and express-handlebars v6.0.2.

Thank you in advance for your help !

    getHomePage: async (req, res) => {
        try {
            const games = await gameModel.find().sort({time: -1}).limit(3).populate('user');
            res.render('home', {title: 'Hello world', games});
        } catch (error) {
            console.error(error);
            res.status(500).json({error});
        }
    }
        <table>
            <thead>
                <th>Position</th>
                <th>Score</th>
                <th>Nom</th>
            </thead>
            <tbody>
                {{#each games}}

                    <tr>
                        <td>#{{@index}}</td>
                        <td>{{this}}</td>
                        <td>{{this.time}}</td>
                    </tr>

                {{/each}}
            </tbody>
        </table>
Bryan BERGER
  • 116
  • 9

2 Answers2

1

Either {{this.time}} or {{time}} should work, see snippet with output below, {{this.team}} and {{time}} is used.

If time still shows nothing, try confirming games is defined as expected.

// shortened data for brevity
const data = {
  games: [
    {team: 'Man U', time: '10am'},
    {team: 'Arsenal', time: '1pm'}
  ]
};

//inline template for snippet simplicity
const template = '' +
'<table>' +
'<thead>' +
'<tr>'+
'<th>#</th>' +
'<th>Team Name</th>' +
'<th>Time</th>' +
'</tr>' +
'</thead>' +
'<tbody>' +
'{{#each games}}' +
'<tr>' +
// BEGIN
'<td>{{@index}}</td>' +
'<td>{{this.team}}</td>' +
'<td>{{time}}</td>' +
// END
'</tr>' +
'{{/each}}' +
'</tbody>' +
'</table>';

var output = Handlebars.compile(template)(data);
console.log(output)
// for snippet simplicity
$('body').html(output);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.7.7/handlebars.min.js"></script>
Grafpaper10
  • 501
  • 3
  • 6
1

I thought the problem came from Handlebars or NodeJS. But it came from my MongoDB request.

I resolved it by adding .lean() at the end of my Mongo request. By default, Mongo returns a document, not a javascript object. So we have to "convert" it to a javascript to allow handlebars to display it:

gameModel.find().sort({time: -1}).limit(3).populate('user').lean()
Bryan BERGER
  • 116
  • 9