Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to have helpers in Hogan.js

I am planning to use Hogan.js for my next project. I was trying to experiment with it a bit. I am just stuck and unable to find out how to use helpers with Hogan.js. I used to use to with Handlebars earlier. Is there a way to have a similar thing on Hogan?

like image 282
Goje87 Avatar asked Dec 13 '13 12:12

Goje87


People also ask

What are Helpers in Handlebars?

Helpers can be used to implement functionality that is not part of the Handlebars language itself. A helper can be registered at runtime via Handlebars. registerHelper , for example in order to uppercase all characters of a string.

What are helpers JavaScript?

Helper functions are JavaScript functions that you can call from your template. Ember's template syntax limits what you can express to keep the structure of your application clear at a glance. When you need to compute something using JavaScript, you can use helper functions.

What is Hogan JS?

Hogan. js is a 3.4k JS templating engine developed at Twitter. Use it as a part of your asset packager to compile templates ahead of time or include it in your browser to handle dynamic templates. If you're developing with Node. js, just use NPM to add the Hogan package.


2 Answers

From hogan.js official website:

Hogan.js was developed against the mustache test suite, so everything that holds true for templates as specified here, is also the case for hogan.js.

Check out the mustache manpage for a thorough explanation of features. Especially the part on lambda expressions.

The following is an example comparison of implementation between hogan.js and handlebars.js.

Template

{{#bold}}
    Willy is awesome.
{{/bold}}

Hogan.js

{
    "bold": function() {
        return function(text, render) {
            return "<b>" + render(text) + "</b>"
        }
    }
}

Handlebars.js

Handlebars.registerHelper('bold', function(options) {
    return new Handlebars.SafeString(
        '<b>' + options.fn(this) + '</b>'
    );
});

Output

<b>Willy is awesome.</b>
like image 166
Mateo Gianolio Avatar answered Sep 26 '22 22:09

Mateo Gianolio


I was having a hard time with this until I found this Hogan issue on Lambdas

It is not longer needed pass render to the helper.

Template

{{#foo}}
    Lets put this text in a html tag.
{{/foo}}

Hogan.js

"foo": function() {
    return function(text) {
        return "<p>" + text + "</p>"
    }

Output

<p>Lets put this text in a html tag.</p>

My problem was a little bit harder since I had:

Template

{{#foo}}
    {{bar}}
{{/foo}}

So the text being passed to the helper was just "{{bar}}" Hogan.js

"foo": function() {
    return function(text) {
// First get the rendered bar variable
        var bar = Hogan.compile(text).render(this));
        return "<p>" + bar + "</p>"
    }
like image 44
SpaceJam Avatar answered Sep 26 '22 22:09

SpaceJam