patrickkettner / grunt-compile-handlebars

grunt plugin to compile static html from a handlebars plugin
MIT License
115 stars 29 forks source link

Block helper that can get optional inner content #72

Open artuze opened 8 years ago

artuze commented 8 years ago

Background on what I'm working on: I'm trying to use G-C-H to help me theme a ZenDesk Help Center. To do so, I need to stub out some of their custom helpers, such as link.

What I can't figure out how to do is write a helper that will work as a block version of the helper, meaning I'd like to do something like {{#link 'help_center'}}Custom link text{{/link}} — I can't figure out how to get that "Custom link text" string available to me within the helper.

Helper I've written so far:

// helpers/link.js
module.exports = function (context, options) {
    // todo:

    if ( options.hasOwnProperty('fn') ) {
        console.log( options.fn() );
    }

    console.log( { 'context': context, 'options': options } );
    return context;
};

yields a result of:


{ context: 'help_center',
  options: 
   { name: 'link',
     hash: {},
     fn: { [Function: prog] program: 1, depth: 0, blockParams: 0 },
     inverse: [Function: noop],
     data: { root: {} } } }

That empty line is the result of the console.log( options.fn() ) line. It's definitely seeing something, because in another part of the template, when I use {{link 'help_center'}}, not as a block, fn doesn't come up.

Ultimately, I just want to generate <a href="#">Custom link text</a> (possibly some other attributes and such, but I'm having good luck so far finding those in places like the options.hash)

Any tips on how I can pull in that wrapped text?

And to further complicate matters, it's possible that wrapped text might include more handlebars tags, which might need to be generated for use somehow too.

(Hope submitting an issue was the right way to go....)

artuze commented 8 years ago

I may have solved my own issue, but I'd love some feedback if there's an easier way that you're aware of.

It was actually very close—options.fn(this) solved it.

Finally ended up with this helper:

// helpers/link.js
hb = require('handlebars');
module.exports = function (context, options) {
    var innerlink = '';

    if ( options.hasOwnProperty('fn') ) {
        innerlink = options.fn(this);
    }

    return new hb.SafeString( [ '<a href="#">', innerlink, '</a>' ].join('') );
};

I'll be adding in key/value defaults in a few, but this seems to work at least.

Like I said, any input on a simpler way or if this is the way, it'd be great to hear.

Thanks! This grunt plugin is super-helpful for this project.

patrickkettner commented 8 years ago

hey @artuze!

are you referencing the defined helper the helper inside of your config?