shannonmoeller / gulp-hb

A sane Gulp plugin to compile Handlebars templates. Useful as a static site generator.

Home Page:http://npm.im/gulp-hb

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Question: Generated content before/after partial

feam-codes opened this issue · comments

Hi,

I‘m looking for a simple way to insert a HTML comment before and after each partial. The comment should contain the filepath to the current partial, with start/end prefix. At the moment i write these comments manually inside each partial with an if-condition to prevent their output in production mode.

Do you have any idea or suggestion how this can be achieved?

Thanks in advance.

This is more of a general Handlebars question than a gulp-hb question. I'd recommend asking this sort of thing on Stack Overflow or by opening an issue in the official Handlebars repo in the future to get a more timely response.

That said, to answer your question, you would need to implement a helper for this. Something like this might work (I haven't tested it, so there may be a bug or two):

// helpers/partial.js

exports.register = function (handlebars) {
    handlebars.registerHelper('partial', function (name, options) {
        let template = handlebars.partials[name];

        // Partial template required
        if (template == null) {
            throw new Error('Missing partial: \'' + name + '\'');
        }

        // Compile partial, if needed
        if (typeof template !== 'function') {
            template = handlebars.compile(template);
        }

        // Render partial
        return '<!-- partial: ' + name + ' -->\n' + template(options.data);
    });
};

Then, in your template, use the helper instead of the partial syntax:

<!-- change this -->
{{> foo}}

<!-- to this -->
{{partial "foo"}}

I hope this helps!