Search code examples
javascriptnode.jsexpresshandlebars.jsexpress-handlebars

How to call functions from html code using express-handlebars?


I´m sure this is a very basic question, but I´m starting with MEAN stack using express-handlebars and still launching my skills.

I´m coming from PHP world and I use to call PHP functions from insede my phtml code, as:

   <p>&copy; 2012 - <?= date('Y') ?> by ACME LLC. All rights reserved.</p>

That would get me the current year and print the following output:

(C) 2012 - 2016by ACME LLC. All rights reserved.

I know handlebars {{ }} would print any context variable, but don´t want to put the current year in the conetext to be printable.

I´ve seen also handlebars helpers, but I´m not sure this is the way to go.

Help appreciated.


Solution

  • As per my understanding you can call a function from html code but you can set helpers to run on server side as well as client side.

    var register = function(Handlebars) {
    
        var helpers = {
            // put all of your helpers inside this object
            foo: function(){
                return "FOO";
            },
            bar: function(){
                return "BAR";
            }
        };
    
        if (Handlebars && typeof Handlebars.registerHelper === "function") {
            // register helpers
            for (var prop in helpers) {
                Handlebars.registerHelper(prop, helpers[prop]);
            }
        } else {
            // just return helpers object if we can't register helpers here
            return helpers;
        }
    
    };
    
    // client
    if (typeof window !== "undefined") {
        register(Handlebars);
    }
    // server
    else {
        module.exports.register = register;
        module.exports.helpers = register(null);
    }