My goal is to change the value of a handlebars variable using the front end JavaScript file.
BackEnd JavaScript (app.js)
res.render('index', { name: 'John' })
.hbs file
<button id="name" onclick="changeName()">{{name}}</button>
script.js (front end)
const changeName = () => {
// Change the value of {{name}} from 'John' to 'Bob'
}
I know you can do it with:
const changeName = () => {
document.getElementById('name').innerHTML = 'Bob'
}
But I specifically want to change the handlebars variable value because in my actual code it is a little more complex.
Thanks!
Take a look to Block helpers handlebars, in your case you can create a helper to change the name variable like this:
.hbs
<div class="entry">
<h1>{{title}}</h1>
<div class="name">
{{#nameHelper}}{{name}}{{/nameHelper}}
</div>
</div>
script.js
Handlebars.registerHelper('nameHelper', function(options) {
return new Handlebars.SafeString(
'<div class="name">'
+ options.fn(otherName)
+ '</div>');
});