Skip to content

Instantly share code, notes, and snippets.

@bjfletcher
Last active October 11, 2016 10:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bjfletcher/9e62dc4ab85964980b8ccbbbcc58e200 to your computer and use it in GitHub Desktop.
Save bjfletcher/9e62dc4ab85964980b8ccbbbcc58e200 to your computer and use it in GitHub Desktop.

Handlebars vs ES 2015

I thought I'd see how Handlebars and Node 6-compatible ES 2015 compare with a few examples.

Example: Conditional and variable

Handlebars

{{#if @root.flags.premiumIndicator}}
	<div>
		{{{premiumLabel}}}
	</div>
{{/if}}

ES 2015

module.exports = ({ premiumIndicator, premiumLabel }} => {
	if (premiumIndicator) {
		return `
			<div>
				${premiumLabel}
			</div>
		`;
	}
};

Example: partials

Handlebars

{{> ads/top }}
{{!-- adType argument passing through as implicit global --}}

ES 2015

module.exports = ({ adType }) => {
	return require('./ads/top')(adType);
};

Example: nested conditionals

Handlebars

{{#if @root.flags.showIndicators}}
	<div>Indicators</div>
	<ul>
	{{#if @root.flags.premiumIndicator}}
		<li>Premium
	{{/if}}
	</ul>
{{/if}}

ES 2015

const indicators = ({ premiumIndicator }) => {
	if (premiumIndicator) {
		return `<div>${premiumLabel}</div>`
	}
};

module.exports = ({ showIndicators, premiumIndicator }} => {
	if (showIndicators) {
		return `
			<div>Indicators</div>
			<ul>
				${indicators(premiumIndicator)}
			</ul>
		`;
	}
};

Example: Unit testing

Handlebars

const fs = require('fs');
const Handlebars = require('handlebars');
const template = fs.readFileSync('ad.hbs', 'utf8');
const result = Handlebars.compile(template)({ adType: 'top' });
expect(result).to.be('<section>It does what it says on the tin</section>');

ES 2015

const result = require('ad')({ adType: 'top' });
expect(result).to.be('<section>It does what it says on the tin</section>');
@bjfletcher
Copy link
Author

Is this any better in terms of readability?

compile`
    ${ helpers.if(flags.indicators) }
        <div>Indicators</div>
        <ul>
        ${ helpers.if(flags.premiumIndicator) }
            <li>Premium
        ${ helpers.endIf() }
        </ul>
    ${ helpers.endIf() }
`;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment