Sign Up for Free

RunKit +

Try any Node.js package right in your browser

This is a playground to test code. It runs a full Node.js environment and already has all of npm’s 400,000 packages pre-installed, including html-template-tag with all npm packages installed. Try it out:

var htmlTemplateTag = require("html-template-tag")

This service is provided by RunKit and is not affiliated with npm, Inc or the package authors.

html-template-tag v3.1.0

ES6 Tagged Template for compiling HTML template strings.

html-template-tag

version Travis Codecov issues downloads license

ES6 Tagged Template for compiling HTML template strings.

Installation

This package is distributed via npm:

npm install html-template-tag

- or -

Download the file src/index.js and add it to your ES6 project.

Usage

String Interpolation

At its core, this module just performs simple ES6 string interpolation.

var html = require("html-template-tag");
// - or - import html from "html-template-tag";

var name = `Antonio`;
var string = html`Hello, ${name}!`;
// "Hello, Antonio!"

Nevertheless, it escapes HTML special characters without refraining its use in loops!

var html = require("html-template-tag");
// - or - import html from "html-template-tag";

var names = ["Antonio", "Megan", "/><script>alert('xss')</script>"];
var string = html`
    <ul>
        ${names.map((name) => html`
            <li>Hello, ${name}!</li>
        `)}
    </ul>
`;
// "<ul><li>Hello, Antonio!</li><li>Hello, Megan!</li><li>Hello, /&gt;&lt;script&gt;alert(&#39;xss&#39;)&lt;/script&gt;!</li></ul>"

Skip autoscaping

You can use double dollar signs in interpolation to mark the value as safe (which means that this variable will not be escaped).

var name = `<strong>Antonio</strong>`;
var string = html`Hello, ${name}!`;
// "Hello, <strong>Antonio</strong>!"

HTML Template Pre-Compiling

This small module can also be used to pre-compile HTML templates:

var html = require("html-template-tag");
// - or - import html from "html-template-tag";

var data = {
    count: 2,
    names: ["Antonio", "Megan"]
};

var template = ({names}) => html`
    <ul>
        ${names.map((name) => html`
            <li>Hello, ${name}!</li>
        `)}
    </ul>
`;

var string = template(data);
/* 
    "
    <ul>
        <li>Hello, Antonio!</li>
        <li>Hello, Megan!</li>
    </ul>
    "
*/

NB: The formating of the string literal is kept.

License

MIT

Thanks

The code for this module has been heavily inspired on Axel Rauschmayer's post on HTML templating with ES6 template strings and Stefan Bieschewski's comment.

Metadata

RunKit is a free, in-browser JavaScript dev environment for prototyping Node.js code, with every npm package installed. Sign up to share your code.
Sign Up for Free