Convert Figma logo to code with AI

handlebars-lang logohandlebars.js

Minimal templating on steroids.

17,914
2,044
17,914
93

Top Related Projects

Logic-less Ruby templates.

Minimal templating on steroids.

Minimal templating with {{mustaches}} in JavaScript

2,915

Asynchronous Javascript templating for the browser and server

A powerful templating engine with inheritance, asynchronous control, and more (jinja2 inspired)

Quick Overview

Handlebars.js is a popular templating engine for JavaScript that extends the Mustache templating language. It allows developers to create semantic templates effectively with minimal coding, providing a powerful way to generate HTML or other text formats from JavaScript objects.

Pros

  • Easy to learn and use, especially for those familiar with Mustache
  • Supports both client-side and server-side rendering
  • Offers built-in helpers and the ability to create custom helpers
  • Provides a precompilation feature for improved performance

Cons

  • Limited logic capabilities compared to some other templating engines
  • Can become complex when dealing with deeply nested data structures
  • Potential performance issues with large datasets if not optimized properly
  • Debugging can be challenging due to the abstraction layer

Code Examples

  1. Basic template usage:
<div class="entry">
  <h1>{{title}}</h1>
  <div class="body">
    {{body}}
  </div>
</div>

This example shows a simple Handlebars template that renders a title and body.

  1. Using built-in helpers:
{{#each items}}
  <li>{{this}}</li>
{{/each}}

This example demonstrates the use of the each helper to iterate over an array of items.

  1. Custom helper:
Handlebars.registerHelper('loudify', function (text) {
  return text.toUpperCase();
});
<h1>{{loudify title}}</h1>

This example shows how to create and use a custom helper that converts text to uppercase.

Getting Started

To use Handlebars.js in your project, follow these steps:

  1. Install Handlebars via npm:

    npm install handlebars
    
  2. In your JavaScript file, require Handlebars:

    const Handlebars = require('handlebars');
    
  3. Create a template and compile it:

    const source = "<p>Hello, {{name}}!</p>";
    const template = Handlebars.compile(source);
    
  4. Use the template with data:

    const result = template({ name: "World" });
    console.log(result); // Outputs: <p>Hello, World!</p>
    

This quick start guide demonstrates how to install Handlebars, create a simple template, and render it with data.

Competitor Comparisons

Logic-less Ruby templates.

Pros of Mustache

  • Simpler syntax and easier to learn for beginners
  • Lightweight and faster rendering in some cases
  • Language-agnostic with implementations in many programming languages

Cons of Mustache

  • Limited functionality compared to Handlebars
  • Lack of built-in helpers and block expressions
  • No support for complex logic or control structures within templates

Code Comparison

Mustache:

{{#items}}
  <li>{{name}}</li>
{{/items}}

Handlebars:

{{#each items}}
  <li>{{this.name}}</li>
{{/each}}

Key Differences

  1. Functionality: Handlebars offers more advanced features like helpers, block expressions, and partials, while Mustache focuses on simplicity.

  2. Logic: Handlebars allows for more complex logic within templates, whereas Mustache is designed to be logic-less.

  3. Learning Curve: Mustache is easier to learn due to its simplicity, while Handlebars requires more time to master its additional features.

  4. Performance: Mustache may have a slight edge in rendering speed for simple templates, but Handlebars can be more efficient for complex scenarios.

  5. Ecosystem: Handlebars has a larger ecosystem with more extensions and integrations, while Mustache maintains a broader language support.

Minimal templating on steroids.

Pros of handlebars.js

  • Lightweight and fast templating engine
  • Extensive documentation and community support
  • Compatible with both server-side and client-side rendering

Cons of handlebars.js

  • Limited built-in helpers compared to some other templating engines
  • Steeper learning curve for complex logic within templates
  • Performance can degrade with large datasets or complex templates

Code Comparison

Both repositories contain the same codebase, as they are the same project. Here's a sample of how Handlebars.js is typically used:

var source = "<p>Hello, {{name}}!</p>";
var template = Handlebars.compile(source);
var context = { name: "John" };
var html = template(context);
// Result: <p>Hello, John!</p>

Summary

Since handlebars-lang/handlebars.js and handlebars-lang/handlebars.js are the same repository, there are no differences to compare. Handlebars.js is a popular templating engine known for its simplicity and flexibility. It allows developers to create reusable templates with minimal logic, promoting separation of concerns between presentation and business logic. While it may have a steeper learning curve for complex scenarios, its widespread adoption and extensive documentation make it a solid choice for many web development projects.

Minimal templating with {{mustaches}} in JavaScript

Pros of Mustache.js

  • Lightweight and simple, with a smaller footprint than Handlebars.js
  • Easier to learn and implement for basic templating needs
  • Language-agnostic, with implementations available in many programming languages

Cons of Mustache.js

  • Limited functionality compared to Handlebars.js, lacking advanced features like helpers and block expressions
  • Less flexibility in template logic, which can lead to more complex view models
  • Smaller community and fewer resources available for support and development

Code Comparison

Mustache.js:

var view = {
  name: "John",
  greeting: function() {
    return "Hello, " + this.name + "!";
  }
};
Mustache.render("{{greeting}}", view);

Handlebars.js:

var source = "<p>{{greeting}}</p>";
var template = Handlebars.compile(source);
var context = {
  greeting: "Hello, World!"
};
var html = template(context);

Both Mustache.js and Handlebars.js are popular templating engines for JavaScript. Mustache.js is simpler and more lightweight, making it easier to learn and implement for basic templating needs. However, Handlebars.js offers more advanced features and flexibility, making it better suited for complex templating requirements. The choice between the two depends on the specific needs of your project and the level of complexity you require in your templates.

2,915

Asynchronous Javascript templating for the browser and server

Pros of Dustjs

  • Asynchronous rendering support, allowing for better performance with large datasets
  • More compact syntax for complex logic and conditionals
  • Built-in support for streaming, which can improve performance for large templates

Cons of Dustjs

  • Steeper learning curve due to its unique syntax and concepts
  • Less active community and fewer resources compared to Handlebars
  • Limited built-in helpers, requiring more custom JavaScript for advanced functionality

Code Comparison

Handlebars:

{{#each items}}
  <li>{{name}}: {{price}}</li>
{{/each}}

Dustjs:

{#items}
  <li>{name}: {price}</li>
{/items}

Both templating engines offer similar basic functionality, but Dustjs's syntax is slightly more concise. Handlebars uses double curly braces and explicit helper names, while Dustjs uses single curly braces and more implicit syntax.

Dustjs excels in handling asynchronous data and streaming, making it potentially more suitable for large-scale applications with complex data requirements. However, Handlebars has a larger community, more extensive documentation, and a gentler learning curve, making it a popular choice for many web development projects.

The choice between the two often depends on specific project requirements, team expertise, and performance considerations.

A powerful templating engine with inheritance, asynchronous control, and more (jinja2 inspired)

Pros of Nunjucks

  • More powerful and flexible syntax, allowing for complex logic and control structures
  • Better performance in rendering templates, especially for large datasets
  • Asynchronous support, enabling non-blocking template rendering

Cons of Nunjucks

  • Steeper learning curve due to more advanced features and syntax
  • Less widespread adoption compared to Handlebars, potentially leading to fewer resources and community support
  • Slightly more verbose syntax for simple use cases

Code Comparison

Handlebars:

{{#each items}}
  <li>{{name}}: {{price}}</li>
{{/each}}

Nunjucks:

{% for item in items %}
  <li>{{ item.name }}: {{ item.price }}</li>
{% endfor %}

Both templating engines offer similar basic functionality, but Nunjucks provides more advanced features like template inheritance, macros, and asynchronous rendering. Handlebars focuses on simplicity and ease of use, making it a good choice for smaller projects or teams new to templating. Nunjucks, on the other hand, offers greater flexibility and power, making it suitable for more complex applications and experienced developers.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

CI Build Status jsDelivr Hits npm downloads npm version Bundle size Install size

Handlebars.js

Handlebars provides the power necessary to let you build semantic templates effectively with no frustration. Handlebars is largely compatible with Mustache templates. In most cases it is possible to swap out Mustache with Handlebars and continue using your current templates.

Checkout the official Handlebars docs site at handlebarsjs.com and try our live demo.

Installing

See our installation documentation.

Usage

In general, the syntax of Handlebars.js templates is a superset of Mustache templates. For basic syntax, check out the Mustache manpage.

Once you have a template, use the Handlebars.compile method to compile the template into a function. The generated function takes a context argument, which will be used to render the template.

var source = "<p>Hello, my name is {{name}}. I am from {{hometown}}. I have " +
             "{{kids.length}} kids:</p>" +
             "<ul>{{#kids}}<li>{{name}} is {{age}}</li>{{/kids}}</ul>";
var template = Handlebars.compile(source);

var data = { "name": "Alan", "hometown": "Somewhere, TX",
             "kids": [{"name": "Jimmy", "age": "12"}, {"name": "Sally", "age": "4"}]};
var result = template(data);

// Would render:
// <p>Hello, my name is Alan. I am from Somewhere, TX. I have 2 kids:</p>
// <ul>
//   <li>Jimmy is 12</li>
//   <li>Sally is 4</li>
// </ul>

Full documentation and more examples are at handlebarsjs.com.

Precompiling Templates

Handlebars allows templates to be precompiled and included as javascript code rather than the handlebars template allowing for faster startup time. Full details are located here.

Differences Between Handlebars.js and Mustache

Handlebars.js adds a couple of additional features to make writing templates easier and also changes a tiny detail of how partials work.

Block expressions have the same syntax as mustache sections but should not be confused with one another. Sections are akin to an implicit each or with statement depending on the input data and helpers are explicit pieces of code that are free to implement whatever behavior they like. The mustache spec defines the exact behavior of sections. In the case of name conflicts, helpers are given priority.

Compatibility

There are a few Mustache behaviors that Handlebars does not implement.

  • Handlebars deviates from Mustache slightly in that it does not perform recursive lookup by default. The compile time compat flag must be set to enable this functionality. Users should note that there is a performance cost for enabling this flag. The exact cost varies by template, but it's recommended that performance sensitive operations should avoid this mode and instead opt for explicit path references.
  • The optional Mustache-style lambdas are not supported. Instead Handlebars provides its own lambda resolution that follows the behaviors of helpers.
  • Handlebars does not allow space between the opening {{ and a command character such as #, / or >. The command character must immediately follow the braces, so for example {{> partial }} is allowed but {{ > partial }} is not.
  • Alternative delimiters are not supported.

Supported Environments

Handlebars has been designed to work in any ECMAScript 2020 environment. This includes

  • Node.js
  • Chrome
  • Firefox
  • Safari
  • Edge

If you need to support older environments, use Handlebars version 4.

Performance

In a rough performance test, precompiled Handlebars.js templates (in the original version of Handlebars.js) rendered in about half the time of Mustache templates. It would be a shame if it were any other way, since they were precompiled, but the difference in architecture does have some big performance advantages. Justin Marney, a.k.a. gotascii, confirmed that with an independent test. The rewritten Handlebars (current version) is faster than the old version, with many performance tests being 5 to 7 times faster than the Mustache equivalent.

Upgrading

See release-notes.md for upgrade notes.

If you are using Handlebars in production, please regularly look for issues labeled possibly breaking. If this label is applied to an issue, it means that the requested change is probably not a breaking change, but since Handlebars is widely in use by a lot of people, there's always a chance that it breaks somebody's build.

Known Issues

See FAQ.md for known issues and common pitfalls.

Handlebars in the Wild

  • apiDoc apiDoc uses handlebars as parsing engine for api documentation view generation.
  • Assemble, by @jonschlinkert and @doowb, is a static site generator that uses Handlebars.js as its template engine.
  • CoSchedule An editorial calendar for WordPress that uses Handlebars.js.
  • Ember.js makes Handlebars.js the primary way to structure your views, also with automatic data binding support.
  • express-handlebars A Handlebars view engine for Express which doesn't suck.
  • express-hbs Express Handlebars template engine with inheritance, partials, i18n and async helpers.
  • Ghost Just a blogging platform.
  • handlebars-action A GitHub action to transform files in your repository with Handlebars templating.
  • handlebars_assets A Rails Asset Pipeline gem from Les Hill (@leshill).
  • handlebars-helpers is an extensive library with 100+ handlebars helpers.
  • handlebars-layouts is a set of helpers which implement extensible and embeddable layout blocks as seen in other popular templating languages.
  • handlebars-loader A handlebars template loader for webpack.
  • handlebars-wax The missing Handlebars API. Effortless registration of data, partials, helpers, and decorators using file-system globs, modules, and plain-old JavaScript objects.
  • hbs An Express.js view engine adapter for Handlebars.js, from Don Park.
  • html-bundler-webpack-plugin The webpack plugin to compile templates, supports Handlebars.
  • incremental-bars adds support for incremental-dom as template target to Handlebars.
  • jblotus created http://tryhandlebarsjs.com for anyone who would like to try out Handlebars.js in their browser.
  • jQuery plugin allows you to use Handlebars.js with jQuery.
  • just-handlebars-helpers A fully tested lightweight package with common Handlebars helpers.
  • koa-hbs koa generator based renderer for Handlebars.js.
  • Marionette.Handlebars adds support for Handlebars and Mustache templates to Marionette.
  • openVALIDATION a natural language compiler for validation rules. Generates program code in Java, JavaScript, C#, Python and Rust with handlebars.
  • Plop is a micro-generator framework that makes it easy to create files with a level of uniformity.
  • promised-handlebars is a wrapper for Handlebars that allows helpers to return Promises.
  • sammy.js by Aaron Quint, a.k.a. quirkey, supports Handlebars.js as one of its template plugins.
  • Swag by @elving is a growing collection of helpers for handlebars.js. Give your handlebars.js templates some swag son!
  • SproutCore uses Handlebars.js as its main templating engine, extending it with automatic data binding support.
  • vite-plugin-handlebars A package for Vite 2. Allows for running your HTML files through the Handlebars compiler.
  • YUI implements a port of handlebars.

External Resources

Have a project using Handlebars? Send us a pull request!

License

Handlebars.js is released under the MIT license.

NPM DownloadsLast 30 Days