Template In Javascript

  1. Javascript Website Templates
  2. Django Template In Javascript
  3. Free Javascript Codes For Websites
  4. Handlebars Template In Javascript File

This article was peer reviewed by Chris Perry and Ritesh Kumar. Thanks to all of SitePoint’s peer reviewers for making SitePoint content the best it can be!

In this article we’re going to give an overview of templating in JavaScript. We’ll first discuss what JavaScript templates are, when we should use them and how we implement them, before going into a bit more detail regarding some of the popular templating engines out there. We’re going to focus on Mustache, Handlebars and jQuery Template.

Feb 17, 2017  The JavaScript Templates project comes with a compilation script, that allows you to compile your templates into JavaScript code and combine them with a minimal Templates runtime into one combined JavaScript file. The compilation script is built for node.js. To use it, first install the JavaScript Templates project via npm.

What Are JavaScript Templates?

JavaScript templates are a method of separating HTML structure from the content contained within. Templating systems generally introduce some new syntax but are usually very simple to work with, especially if we’ve used templating systems elsewhere previously (eg. Twig in PHP). A fun point to note is that token replacement is usually symbolized by double curly brackets ({{ ... }}), which Mustache and Handlebars derive their names from (hint: turn them sideways to see the similarity).

When Should We Use JavaScript Templates?

  1. Generate valid HTML5 and CSS3 website templates with just a few mouse clicks!
  2. Jan 28, 2019  Template literals are string literals allowing embedded expressions. You can use multi-line strings and string interpolation features with them. They were called 'template strings' in prior editions of the ES2015 specification.

As soon as we find ourselves including HTML inside JavaScript strings we should be starting to think about what benefits JavaScript templates could give us. Separation of concerns is of utmost importance when building a maintainable codebase, so anything which can help us achieve this should be explored. In front-end web development this is epitomized when separating HTML from JavaScript (this works both ways in that we shouldn’t include JavaScript inline in HTML).

Some common scenarios which could benefit from JavaScript templates are real-time web apps (for example a live streaming app for event commentary), or internationalization (i18n), which will quite often require that different content is displayed using the same formatting.

How Do We Implement JavaScript Templates?

We’ll go into more detail on this with specific library examples, but essentially it’s as simple as including our chosen library, fetching our template and rendering it alongside some data.

Most libraries support both inline and external templates. Inline templates are great for when we’ve got very few templates or we know that we’ll be using the included templates on each page load, but generally our templates should be external. External templates bring many benefits, chiefly that templates will never be downloaded to the client unless they are needed by the page.

mustache.js

Mustache is a multi-language, logic-less templating system. The mustache.js implementation is just one of many. So once we’re used to the (very simple) syntax, we can use it in a variety of programming languages.

Key Points

  • 9kb file size (small)
  • Simple
  • No dependencies
  • No logic
  • No precompiled templates
  • Programming language agnostic

Example

See the Pen Mustache.js example by SitePoint (@SitePoint) on CodePen.

As you can see in this example, the Mustache.render function takes two parameters: the Mustache template, as well as a view object that contains the data and code needed to render the template. In this case we are replacing name and a power variables with simple strings, but it’s possible to do much more. For example loop over an array, or make use of a special rendering function that uses the current view as its view argument.

mustache.js is perfect for small projects and quick prototypes where templating complexity is at a minimum. A key thing to note is that we can start off a project with mustache.js and then easily upgrade to Handlebars.js later as the templates are (mostly) the same.

If you would like to read more about Mustache, check out: Creating HTML Templates with Mustache.js.

Handlebars.js

Handlebars.js is built on top of Mustache and is mostly compatible with Mustache templates. In a nutshell, it provides everything mustache.js provides, plus it supports block expressions and precompiled templates. Precompiled templates are a big deal as they increase performance by a large margin (in a rough performance test, precompiled Handlebars.js templates rendered in about half the time of Mustache templates). Block expressions allow you to include more logic in your templates; one of the more common examples of these are advanced iterators — eg. create a <ul> list iterator which wraps each item in <li>. You can read more about block expressions here.

Key Points

  • 86kb file size (large), or 18kb if using precompiled templates
  • Block expressions (helpers)
  • Precompiled templates
  • No dependencies

Example

See the Pen Handlebars.js Example by SitePoint (@SitePoint) on CodePen

Handlebars.js is perfect for projects where performance is important and we are not hugely worried about adding 18kb to the weight of the page. It’s also the way to go if we want to make use of block expressions.

Note that to see the performance benefits of Handlebars.js (and the greatly reduced file size) we must use precompiled templates. In order to do so efficiently we should add Handlebars.js template compilation into our build process (Grunt has a great plug-in for this).

If you would like to find out more about Handlebars, check out: A Beginner’s Guide to Handlebars.

jQuery Template

jQuery Template is not as popular as mustache.js or Handlebars.js but we should not overlook it. The templates are different to Mustache templates as they are just plain HTML with no new syntax. Instead of token replacement techniques it uses data attributes to indicate where data should be inserted in the HTML fragment.

Key Points

  • 7kb file size (small)
  • Requires jQuery (+82kb)
  • Simple, but different to how Mustache and Handlebars.js work
  • No precompiled templates

Example

See the Pen jQuery Template example by SitePoint (@SitePoint) on CodePen.

jQuery Template is ideal for projects which are already including jQuery as the file size is very small. However if your project is not going to utilise jQuery then it’s hard to recommend considering the total file size.

Other Options

There are of course many other solutions to this problem which we won’t cover in detail in this article. Here’s a very quick overview of some other popular choices;

Underscore.js

Underscore is a popular JavaScript library which provides templating functions amongst a myriad of other features. By default it does not use the double curly bracket syntax used by Mustache, instead opting for ERB-style delimiters (<% ... %>).

Embedded JS Templates (EJS)

Like Underscore.js, Embedded JS Templates uses ERB-style syntax for templates. One thing to note with EJS is that templates must be external files – they cannot be inline.

Closing Remarks

So which is the best? Like most development problems, there’s no silver bullet. It depends on many things;

  • Are you already using jQuery in your project?
  • Which templating systems do you have previous experience with?
  • Do you want to keep logic out of the templates?
  • How worried are you about total page file size?
  • How worried are you about performance/Does your website need to support low-power devices?

Once we’ve thought about those factors we can make an educated choice from the list above. However as briefly mentioned before, a good flexible strategy would be to implement mustache.js first and then swap to Handlebars.js later if the added functionality or performance benefits are needed.

Want to chime in? Please leave a comment below!

Contents

  • Usage
  • API
  • Templates syntax

Demo

Description

1KB lightweight, fast & powerful JavaScript templating engine with zerodependencies. Compatible with server-side environments like Node.js, moduleloaders like RequireJS, Browserify or webpack and all web browsers.

Usage

Client-side

Include the (minified) JavaScript Templates script in your HTML markup:

Add a script section with type 'text/x-tmpl', a unique id property andyour template definition as content:

'o' (the lowercase letter) is a reference to the data parameter of thetemplate function (see the API section on how to modify this identifier).

In your application code, create a JavaScript object to use as data for thetemplate:

In a real application, this data could be the result of retrieving aJSON resource.

Render the result by calling the tmpl() method with the id of the templateand the data object as arguments:

Server-side

The following is an example how to use the JavaScript Templates engine on theserver-side with node.js.

Javascript template literals

Create a new directory and add the tmpl.js file. Or alternatively, installthe blueimp-tmpl package with npm:

Add a file template.html with the following content:

Add a file server.js with the following content:

Run the application with the following command:

Requirements

The JavaScript Templates script has zero dependencies.

API

tmpl() function

The tmpl() function is added to the global window object and can becalled as global function:

The tmpl() function can be called with the id of a template, or with atemplate string:

If called without second argument, tmpl() returns a reusable templatefunction:

Templates cache

Templates loaded by id are cached in the map tmpl.cache:

Output encoding

The method tmpl.encode is used to escape HTML special characters in thetemplate output:

tmpl.encode makes use of the regular expression tmpl.encReg and theencoding map tmpl.encMap to match and replace special characters, which canbe modified to change the behavior of the output encoding.
Strings matched by the regular expression, but not found in the encoding map areremoved from the output. This allows for example to automatically trim inputvalues (removing whitespace from the start and end of the string):

Local helper variables

The local variables available inside the templates are the following:

  • o: The data object given as parameter to the template function (see thenext section on how to modify the parameter name).
  • tmpl: A reference to the tmpl function object.
  • _s: The string for the rendered result content.
  • _e: A reference to the tmpl.encode method.
  • print: Helper function to add content to the rendered result string.
  • include: Helper function to include the return value of a differenttemplate in the result.

To introduce additional local helper variables, the string tmpl.helper canbe extended. The following adds a convenience function for console.log and astreaming function, that streams the template rendering result back to thecallback argument (note the comma at the beginning of each variabledeclaration):

Those new helper functions could be used to stream the template contents to theconsole output:

Template function argument

The generated template functions accept one argument, which is the data objectgiven to the tmpl(id, data) function. This argument is available inside thetemplate definitions as parameter o (the lowercase letter).

The argument name can be modified by overriding tmpl.arg:

Javascript website templates

Template parsing

The template contents are matched and replaced using the regular expressiontmpl.regexp and the replacement function tmpl.func. The replacementfunction operates based on theparenthesized submatch strings.

To use different tags for the template syntax, override tmpl.regexp with amodified regular expression, by exchanging all occurrences of '{%' and '%}',e.g. with '[%' and '%]':

By default, the plugin preserves whitespace (newlines, carriage returns, tabsand spaces). To strip unnecessary whitespace, you can override the tmpl.funcfunction, e.g. with the following code:

Templates syntax

Interpolation

Print variable with HTML special characters escaped:

Print variable without escaping:

Print output of function calls:

Use dot notation to print nested properties:

Evaluation

Use print(str) to add escaped content to the output:

Use print(str, true) to add unescaped content to the output:

Use include(str, obj) to include content from a different template:

Javascript Website Templates

If else condition:

For loop:

Compiled templates

The JavaScript Templates project comes with a compilation script, that allowsyou to compile your templates into JavaScript code and combine them with aminimal Templates runtime into one combined JavaScript file.

The compilation script is built for node.js.
To use it, first install the JavaScript Templates project vianpm:

This will put the executable tmpl.js into the folder node_modules/.bin.It will also make it available on your PATH if you install the package globally(by adding the -g flag to the install command).

The tmpl.js executable accepts the paths to one or multiple template filesas command line arguments and prints the generated JavaScript code to theconsole output. The following command line shows you how to store the generatedcode in a new JavaScript file that can be included in your project:

The files given as command line arguments to tmpl.js can either be puretemplate files or HTML documents with embedded template script sections. For thepure template files, the file names (without extension) serve as template ids.
The generated file can be included in your project as a replacement for theoriginal tmpl.js runtime. It provides you with the same API and provides atmpl(id, data) function that accepts the id of one of your templates asfirst and a data object as optional second parameter.

Django Template In Javascript

Tests

The JavaScript Templates project comes withUnit Tests.
There are two different ways to run the tests:

  • Open test/index.html in your browser or
  • run npm test in the Terminal in the root path of the repository package.

The first one tests the browser integration, the second one thenode.js integration.

Javascript

Free Javascript Codes For Websites

License

Handlebars Template In Javascript File

The JavaScript Templates script is released under theMIT license.