Recently I worked on a project where clojure was used on the back end and javascript on the front end. Handlebars was used for front end templating. However, at some point a need emerged to do some server side rendering. Wanting to keep things DRY we looked for a solution that would allow us to have same templates both server and client side.
What we found was clojure library called hbs. Hbs is a wrapper around handlebars.java that allows handlebars templates to be rendered server side.
Most important thing is the render-function. It takes template and context as parameters and returns compiled result.
(use '[hbs.core])
(render "<h1>{{title}}<h1>" {:title "Hello"}); => <h1>Hello<h1>
You can define helpers with clojure using defhelper-macro
(use '[hbs.helper])
(defhelper dollars [amount options] (format "$%,d" amount))
(render "{{dollars amt}}" {:amt 12345}); => "$12,345"
or you can use regular javascript helpers by loading the javascript-file which defines helpers
//helpers.js
(Handlebars.registerHelper('dollars', function (amount) {
return "$"+amount.toLocaleString();
});
(register-javascript-helpers! "helpers.js")
(render "{{dollars amt}}" {:amt 12345}); => "$12345"
That's it. Nothing fancy but worked well for our case. I hope you might find it useful as well.
Software professional with a passion for quality. Likes TDD and working in agile teams. Has worked with wide-range of technologies, backend and frontend, from C++ to Javascript. Currently very interested in functional programming.