Hysen Labs
Open-source project
71104/jquery-handlebars avatar
71104

jquery-handlebars

A jQuery plugin to render Handlebars.js templates into elements

100 stars38 forksJavaScriptMIT
01
DEEP OPEN-SOURCE ANALYSIS

jquery-handlebars: one render call per element

A small jQuery plugin that gives every element a render method, so you pass a template name and a context and the compiled Handlebars output lands straight in the page.

02
DEEP OPEN-SOURCE ANALYSIS

What render does

Each jQuery object gets a render method that handles the full loop: retrieve the named template, either from cache or by fetching it over AJAX and compiling it with Handlebars, render it against the context object you supply, and pass the resulting string to the element's html method. The plugin exists to collapse that sequence into a single call, and the output ends up replacing whatever the element currently holds.

03
DEEP OPEN-SOURCE ANALYSIS

How a name becomes a path

The first argument is a template name, and the plugin builds the fetch path from it by prepending a base path and appending a file extension. The defaults are an empty base path and a .handlebars extension, so a developer deals with names rather than full paths. Both can be changed through the jQuery.handlebars method, which is where that path logic gets configured.

04
DEEP OPEN-SOURCE ANALYSIS

Helpers and partials stay normal

Nothing about the plugin forces you out of the Handlebars namespace. Helpers and partials can be registered as usual. Partials can also be fetched and registered through the plugin by configuring their base path and filename extension in the same jQuery.handlebars call, and a shorthand registers all partials at initialization time via a partials setting.

05
DEEP OPEN-SOURCE ANALYSIS

The context argument

The second argument is the context Handlebars uses to render the template. It ties the template name and the data together into the final HTML, which then fills the element's content. Between the name, the path, and the context, the plugin keeps the fiddly parts of template loading out of the caller's way, which is the practical appeal of the whole thing.

07
DEEP OPEN-SOURCE ANALYSIS

Official sources

08
Community notes

Community notes