I set up a simple form input page where after submitting the form, the same form data would be displayed as entries under.
const express = require('express');
const router = express.Router();
const view = 'users';
const data = [];
const croute = '/users';
router
.route(croute)
.get((req, res) => res.render(view, { udat: data }))
.post((req, res) => {
const {name, age} = req.body;
data.push({name, age});
console.log(data);
res.redirect(croute);
});
module.exports = router;
The view hbs is set up as below,
<form action="/users" method="POST">
<div>
<label>
Name:
<input type="text" name="name" required/>
</label>
</div>
<div>
<label>
Age:
<input type="number" name="age" required/>
</label>
</div>
<div> <button type="submit"> Submit </button> </div>
</form>
{{#isEmpty udat}}
<h4> There are no users yet. Add Some. </h4>
{{else}}
<table>
<thead>
<tr>
<td> No. </td>
<td>Name</td>
<td>Age</td>
</tr>
</thead>
<tbody>
{{#each udat}}
<tr>
<td>{{@index}}</td>
<td>{{name}}</td>
<td>{{age}}</td>
</tr>
{{/each}}
</tbody>
</table>
{{/isEmpty}}
The block helper:
hbs.registerHelper('isEmpty', (arg, options) => {
return arg.length <= 0 ? options.fn(this) : options.inverse(this);
});
For reasons I don't know, the part with {{#each}}
wont get rendered. Even though the <thead>
part gets rendered. This shows a sign that the data was indeed saved on the server. Prior, the first else
condition is rendered with no problem when there was no users yet.
When used without the block helper branching, the table itself with plain {{each}}
would show the entries without problem. But as soon as nested under the block helper, it acts up and {{each}}
stops rendering.
Your isEmpty
helper is using an arrow function and since:
Arrow functions don't have their own bindings to this, arguments, or super, and should not be used as methods.
in addition:
they inherit this from the parent scope at the time they are defined.
That means when you use this
in your callback function to the helper, this
is not referring to what you think it is.
You can try to switch to just using a regular old function expression like this:
hbs.registerHelper('isEmpty', function(arg, options) {
return arg.length <= 0 ? options.fn(this) : options.inverse(this);
});
Alternatively just use {{#each}}
with {{else}}
and you won't need the helper. The @first
and @last
run as the first or last iteration of the loop:
{{#each udat}}
{{#if @first}}
<table>
<thead>
<tr>
<td>No.</td>
<td>Name</td>
<td>Age</td>
</tr>
</thead>
<tbody>
{{/if}}
<tr>
<td>{{@index}}</td>
<td>{{name}}</td>
<td>{{age}}</td>
</tr>
{{#if @last}}
</tbody>
</table>
{{/if}}
{{else}}
<h4>There are no users yet. Add Some.</h4>
{{/each}}