1

I am trying to use Handlebars on Nodejs.

I can execute plain vars but what if I want to execute javascript code to output some values? In PHP we would do this :

<div>This is formatted date : &lt;?php echo date($oldDate); ?&gt; </div>

Example in nodejs handlebars:

<div>This is non formatted date: {{olddate}}</div>
<div>This is formatted date : {{ date(olddate)}}</div>

I know that in EJS template engine we can do this by putting inside <% like this

<div>This is formatted date : <% date(olddate)%></div>

Thank you for your answers

2
  • Thanks Jonathan, So basically, I can create a custom helper and use it. Commented Feb 22, 2016 at 5:53
  • @Jonathan Please write this as an answer so I can choose it. Commented Feb 22, 2016 at 6:04

1 Answer 1

1

Handlebars doesn't support executing JavaScript expressions, including function calls, within the template. This is likely because it was inspired by Mustache's "logic-less templates," adding only a minimal amount of logic.

What is uses instead are helpers:

<div>This is formatted date : {{date olddate}}</div>

And, it allows you to define your own using Handlebars.registerHelper():

Handlerbars.registerHelper('date', function (dateValue) {
    return new Date(dateValue).toString();
});

Example: https://jsfiddle.net/sznkd4eo/

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.