Caramel how to register handlebars helper?

109 views Asked by At

I'm using Jaggery.js writing a web app and using caramel as the MVC framework. Caramel uses Handlebars as the render engine so that we can use any built in helpers provided by handlebars, such as {{#each}}, {{#if}}, etc.

But how can I write my custom helpers and register in caramel, so caramel can use it render in the template ?

Is there any samples regarding this ?

Thanks in advance!

1

There are 1 answers

0
dereck On BEST ANSWER

I found a way to register handlebars helper in caramel and it can work, but not sure whether is the normal and correct solution.

What i was doing is register the helper in the caramel theme.js (jaggeryapps\myapp\themes\mytheme\theme.js), code is like below:

var engine = caramel.engine('handlebars', (function () {
    return {
        partials: function (Handlebars) {
            var theme = caramel.theme();
            var partials = function (file) {
                (function register(prefix, file) {
                    var i, length, name, files;
                    if (file.isDirectory()) {
                        files = file.listFiles();
                        length = files.length;
                        for (i = 0; i < length; i++) {
                            file = files[i];
                            register(prefix ? prefix + '.' + file.getName() : file.getName(), file);
                        }
                    } else {
                        name = file.getName();
                        if (name.substring(name.length - 4) !== '.hbs') {
                            return;
                        }
                        file.open('r');
                        Handlebars.registerPartial(prefix.substring(0, prefix.length - 4), file.readAll());
                        file.close();
                    }
                })('', file);
            };

            partials(new File(theme.resolve('partials')));


            Handlebars.registerHelper('my-for', function(n, block) {
                var ret = '';

                for(var i = 0; i < n; ++i) {
                    ret += block.fn(i);
                }

                return ret;
            });

        },
    };
}()));