3

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!

1 Answer 1

1

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>');
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.