javascript in templates/handlebars?
-
Hey folks,
I need to format a datetime item in a template. I have data coming in a JSON from a REST API. It's patient info. I loop over patients with {{#each patients}}. The data element is called p2_dob. I'd like to do something like this:
{{formatMuhDate(p2_dob)}}
or something. Can I do this? Is it allowed? I'm new to handlebars.
-
yes, you can do that. the right syntax will be
{{formatMuhDate p2_dob}}
, you can see in this example https://playground.jsreport.net/w/admin/hBfqC7af (at the bottom) how the helpers functions are defined, for your case your can define something like:function formatMuhDate (dateVar) { // use js to get the date in string format you want return dateVar }
-
Ah, I see. I was just reading handlebars' docs and they say this can't be done. Maybe it was an old page? Or have you added this functionality to be more like jsrender? I was about to switch to jsrender, but if I don't need to, I won't. Thanks for the reply!
-
One more question. Can I bring in modules in that section where the functions are defined? In particular, I'd like to use the moment module.
-
Ah, got it. Never mind. Sorry I'm so obtuse sometimes.
-
Or have you added this functionality to be more like jsrender?
the only thing we added is that there is one common way to define helpers no matter which template engine is being used, and that common way is defining javascript functions. so those functions work on jsrender, handlerbars, pug, etc.
Maybe it was an old page?
maybe, but i'm not sure if you refer to the way of calling the helper (syntax) or the way of defining the functions. we just added a common way to define the helpers across any template engine.