This project has moved and is read-only. For the latest updates, please go here.

How to register new helper in .hbs file for handlebar

Jul 7, 2016 at 10:44 AM
Hi

I need my own java script function for formatting something while rendering data in template. I know handle bar allows us to write helpers for the same as below.

Handlebars.registerHelper("formatDate", function(inputDate) {
    return inputDate;
});
I tried doing this in script section under .hbs file but it is not getting registered.

Please advice
Jul 7, 2016 at 11:40 AM
Hi,

OpenContent use Serverside handlebars and clientside handlebars (for items in lists).

1) In serverside handlebars you can only use existing helpers.
{{formatDateTime "dd/MMM/yy" "nl-NL" }}
2) In clientside handlebars you can add your helpers in the javascript file of the template.
if (typeof Handlebars != 'undefined') {
        Handlebars.registerHelper('formatDateTime', function (context, format) {

            if (window.moment && context && moment(context).isValid()) {

                var f = format || "DD/MM/YYYY";

                return moment(context).format(f);

            } else {

                return context;   //  moment plugin is not available, context does not have a truthy value, or context is not a valid date

            }

        });

       
    }
You can find an example in the articles template.
http://www.openextensions.net/templates/open-content/articles


For more help :

https://opencontent.readme.io/docs/tokens
Jul 7, 2016 at 12:40 PM
Thanks for you help.

Its working as per my expectation