• This repository has been archived on 26/Sep/2021
  • Stars
    star
    1,721
  • Rank 27,118 (Top 0.6 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created about 13 years ago
  • Updated about 3 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

1KB lightweight, fast & powerful JavaScript templating engine with zero dependencies. Compatible with server-side environments like node.js, module loaders like RequireJS and all web browsers.

JavaScript Templates

Contents

Description

1KB lightweight, fast & powerful JavaScript templating engine with zero dependencies.
Compatible with server-side environments like Node.js, module loaders like RequireJS or webpack and all web browsers.

Usage

Client-side

Install the blueimp-tmpl package with NPM:

npm install blueimp-tmpl

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

<script src="js/tmpl.min.js"></script>

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

<script type="text/x-tmpl" id="tmpl-demo">
  <h3>{%=o.title%}</h3>
  <p>Released under the
  <a href="{%=o.license.url%}">{%=o.license.name%}</a>.</p>
  <h4>Features</h4>
  <ul>
  {% for (var i=0; i<o.features.length; i++) { %}
      <li>{%=o.features[i]%}</li>
  {% } %}
  </ul>
</script>

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

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

var data = {
  title: 'JavaScript Templates',
  license: {
    name: 'MIT license',
    url: 'https://opensource.org/licenses/MIT'
  },
  features: ['lightweight & fast', 'powerful', 'zero dependencies']
}

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

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

document.getElementById('result').innerHTML = tmpl('tmpl-demo', data)

Server-side

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

Install the blueimp-tmpl package with NPM:

npm install blueimp-tmpl

Add a file template.html with the following content:

<!DOCTYPE HTML>
<title>{%=o.title%}</title>
<h3><a href="{%=o.url%}">{%=o.title%}</a></h3>
<h4>Features</h4>
<ul>
{% for (var i=0; i<o.features.length; i++) { %}
    <li>{%=o.features[i]%}</li>
{% } %}
</ul>

Add a file server.js with the following content:

require('http')
  .createServer(function (req, res) {
    var fs = require('fs'),
      // The tmpl module exports the tmpl() function:
      tmpl = require('./tmpl'),
      // Use the following version if you installed the package with npm:
      // tmpl = require("blueimp-tmpl"),
      // Sample data:
      data = {
        title: 'JavaScript Templates',
        url: 'https://github.com/blueimp/JavaScript-Templates',
        features: ['lightweight & fast', 'powerful', 'zero dependencies']
      }
    // Override the template loading method:
    tmpl.load = function (id) {
      var filename = id + '.html'
      console.log('Loading ' + filename)
      return fs.readFileSync(filename, 'utf8')
    }
    res.writeHead(200, { 'Content-Type': 'text/x-tmpl' })
    // Render the content:
    res.end(tmpl('template', data))
  })
  .listen(8080, 'localhost')
console.log('Server running at http://localhost:8080/')

Run the application with the following command:

node server.js

Requirements

The JavaScript Templates script has zero dependencies.

API

tmpl() function

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

var result = tmpl('tmpl-demo', data)

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

var result = tmpl('<h3>{%=o.title%}</h3>', data)

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

var func = tmpl('<h3>{%=o.title%}</h3>')
document.getElementById('result').innerHTML = func(data)

Templates cache

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

var func = tmpl('tmpl-demo'), // Loads and parses the template
  cached = typeof tmpl.cache['tmpl-demo'] === 'function', // true
  result = tmpl('tmpl-demo', data) // Uses cached template function

tmpl.cache['tmpl-demo'] = null
result = tmpl('tmpl-demo', data) // Loads and parses the template again

Output encoding

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

var output = tmpl.encode('<>&"\'\x00') // Renders "&lt;&gt;&amp;&quot;&#39;"

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

tmpl.encReg = /(^\s+)|(\s+$)|[<>&"'\x00]/g
var output = tmpl.encode('    Banana!    ') // Renders "Banana" (without whitespace)

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 the next 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 different template in the result.

To introduce additional local helper variables, the string tmpl.helper can be extended. The following adds a convenience function for console.log and a streaming function, that streams the template rendering result back to the callback argument (note the comma at the beginning of each variable declaration):

tmpl.helper +=
  ',log=function(){console.log.apply(console, arguments)}' +
  ",st='',stream=function(cb){var l=st.length;st=_s;cb( _s.slice(l));}"

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

<script type="text/x-tmpl" id="tmpl-demo">
  <h3>{%=o.title%}</h3>
  {% stream(log); %}
  <p>Released under the
  <a href="{%=o.license.url%}">{%=o.license.name%}</a>.</p>
  {% stream(log); %}
  <h4>Features</h4>
  <ul>
  {% stream(log); %}
  {% for (var i=0; i<o.features.length; i++) { %}
      <li>{%=o.features[i]%}</li>
      {% stream(log); %}
  {% } %}
  </ul>
  {% stream(log); %}
</script>

Template function argument

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

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

tmpl.arg = 'p'

// Renders "<h3>JavaScript Templates</h3>":
var result = tmpl('<h3>{%=p.title%}</h3>', { title: 'JavaScript Templates' })

Template parsing

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

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

tmpl.regexp = /([\s'\\])(?!(?:[^[]|\[(?!%))*%\])|(?:\[%(=|#)([\s\S]+?)%\])|(\[%)|(%\])/g

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

var originalFunc = tmpl.func
tmpl.func = function (s, p1, p2, p3, p4, p5, offset, str) {
  if (p1 && /\s/.test(p1)) {
    if (
      !offset ||
      /\s/.test(str.charAt(offset - 1)) ||
      /^\s+$/g.test(str.slice(offset))
    ) {
      return ''
    }
    return ' '
  }
  return originalFunc.apply(tmpl, arguments)
}

Templates syntax

Interpolation

Print variable with HTML special characters escaped:

<h3>{%=o.title%}</h3>

Print variable without escaping:

<h3>{%#o.user_id%}</h3>

Print output of function calls:

<a href="{%=encodeURI(o.url)%}">Website</a>

Use dot notation to print nested properties:

<strong>{%=o.author.name%}</strong>

Evaluation

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

<span>Year: {% var d=new Date(); print(d.getFullYear()); %}</span>

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

<span>{% print("Fast &amp; powerful", true); %}</span>

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

<div>
  {% include('tmpl-link', {name: "Website", url: "https://example.org"}); %}
</div>

If else condition:

{% if (o.author.url) { %}
<a href="{%=encodeURI(o.author.url)%}">{%=o.author.name%}</a>
{% } else { %}
<em>No author url.</em>
{% } %}

For loop:

<ul>
{% for (var i=0; i<o.features.length; i++) { %}
    <li>{%=o.features[i]%}</li>
{% } %}
</ul>

Compiled templates

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:

npm install blueimp-tmpl

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 files as command line arguments and prints the generated JavaScript code to the console output. The following command line shows you how to store the generated code in a new JavaScript file that can be included in your project:

tmpl.js index.html > tmpl.js

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

Tests

The JavaScript Templates project comes with Unit 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 the Node.js integration.

License

The JavaScript Templates script is released under the MIT license.

More Repositories

1

jQuery-File-Upload

File Upload widget with multiple file selection, drag&drop support, progress bar, validation and preview images, audio and video for jQuery. Supports cross-domain, chunked and resumable file uploads. Works with any server-side platform (Google App Engine, PHP, Python, Ruby on Rails, Java, etc.) that supports standard HTML form file uploads.
PHP
30,963
star
2

JavaScript-MD5

JavaScript MD5 implementation. Compatible with server-side environments like node.js, module loaders like RequireJS and all web browsers.
JavaScript
4,549
star
3

JavaScript-Load-Image

Load images provided as File or Blob objects or via URL. Retrieve an optionally scaled, cropped or rotated HTML img or canvas element. Use methods to parse image metadata to extract IPTC and Exif tags as well as embedded thumbnail images, to overwrite the Exif Orientation value and to restore the complete image header after resizing.
JavaScript
4,449
star
4

Gallery

blueimp Gallery is a touch-enabled, responsive and customizable image & video gallery, carousel and lightbox, optimized for both mobile and desktop web browsers. It features swipe, mouse and keyboard navigation, transition effects, slideshow functionality, fullscreen support and on-demand content loading.
JavaScript
3,745
star
5

Bootstrap-Image-Gallery

This project is deprecated in favor of blueimp Gallery.
HTML
2,830
star
6

JavaScript-Canvas-to-Blob

JavaScript Canvas to Blob is a function to convert canvas elements into Blob objects.
JavaScript
1,468
star
7

wdio

Docker setup for WebdriverIO with automatic screenshots, image diffing and screen recording support for containerized versions of Chrome and Firefox on Linux, mobile versions of Chrome and Firefox on Android as well as Safari on iOS, Safari on macOS and Edge on Windows.
JavaScript
295
star
8

aws-lambda

Collection of functions for AWS Lambda
JavaScript
270
star
9

jQuery-Image-Gallery

This project is deprecated in favor of blueimp Gallery.
HTML
175
star
10

shell-scripts

A collection of (mostly POSIX compatible) shell scripts.
Shell
135
star
11

nightwatch

This project is deprecated in favor of blueimp/wdio.
134
star
12

mjpeg-server

MJPEG Server implements MJPEG over HTTP using FFmpeg or any other input source capable of piping a multipart JPEG stream to stdout. Its primary use case is providing Webdriver screen recordings.
Go
99
star
13

aws-smtp-relay

SMTP server to relay emails via Amazon SES or Amazon Pinpoint using IAM roles.
Go
76
star
14

record-screen

Node.js screen recording function for remote servers using ffmpeg.
JavaScript
71
star
15

nightwatch-video-recorder

Record videos of Nightwatch.js test sessions. Uses ffmpeg to capture a (remote) webdriver desktop screen.
JavaScript
41
star
16

mailhog-node

A NodeJS library to interact with the MailHog API. MailHog is a stand-in SMTP server for Web and API based SMTP testing.
JavaScript
35
star
17

ffmpeg-image-diff

An image diffing library using FFmpeg. Creates an image showing perceptual differences and returns SSIM data.
JavaScript
30
star
18

chromedriver

Chromedriver Dockerfile
Dockerfile
21
star
19

basedriver

Base Webdriver Dockerfile
Dockerfile
14
star
20

passphrase

Better passwords by combining random words.
Go
13
star
21

phpbb

phpBB Dockerfile
Shell
12
star
22

nightwatch-browserstack

Nightwatch.js module to update BrowserStack session status for failed tests.
JavaScript
11
star
23

playwright-example

Example setup for the Playwright end-to-end testing framework. Includes an example email application with file attachment support and tests to cover its functionality.
TypeScript
10
star
24

adb-record-screen

Screen recording function using Android Debug Bridge (adb).
JavaScript
8
star
25

wdio-screen-commands

Webdriver.io commands to capture and record browser screens.
JavaScript
8
star
26

geckodriver

Geckodriver Dockerfile
Dockerfile
4
star
27

wildcard-redirect

HTTP service to redirect wildcard subdomains of an origin host to a new target host, e.g. *.example.com to *.example.org.
Go
4
star
28

mocha-chrome

mocha-chrome Dockerfile
Shell
3
star
29

blueimp.github.io

blueimp's GitHub projects
3
star
30

phpbb-s3-backup

phpBB S3 Backup Dockerfile
Shell
2
star