encode-html-template-tag

    2.5.0 • Public • Published

    encode-html-template-tag

    A simple but flexible template tagging function.

    • Create templates that automatically encode passed-in variables
    • Nest templates without fear of double encoding them
    • Handles variables that are arrays, promises, or combinations
    • Replace variables at render time
    • Create a tag that uses a custom encoding function

    With thanks to the developers of escape-html-template-tag for the inspiration.

    Changes in version 2

    • Private fields have been removed so this package now works in browsers and earlier node versions.
    • The render() function now always returns a promise
    • Introduced a generate() function that returns an async iterable

    How to use

    There are two main ways to generate tempaltes: as a promise and as an async iterator

    Promise

    Perform the transformations and concatenate all into one string using the render function.

    const html = require('encode-html-template-tag');
    
    const message = 'I <3 horses';
    const para = html`<p>${message}</p>`;
    await para.render() // <p>I &lt;3 horses</p>;

    Async iterator

    THe generate function returns an async iterator. Useful in node JS when dealing with streams:

    const { Readable } = require('stream');
    const html = require('encode-html-template-tag');
    
    module.exports = async (req, res) => {
    	const template = html`Thanks for visiting, the date and time is ${new Date())}.`;
    
    	Readable.from(template.generate()).pipe(res);
    };

    Examples

    const html = require('encode-html-template-tag');
    
    const div = html`<div>${para}</div>`;
    await div.render() // <div><p>I &lt;3 horses</p></div>
    
    const promise = Promise.resolve('Hello!');
    const array = [1,2,Promise.resolve(3)];
    
    const component = html`<b>${promise}</b><i>${array}</i>`;
    await component.render(); // <b>Hello!</b><i>123</i>
    
    // Create a translatable data type
    const t = text => {
    	return {
    		translatable: true,
    		toString(){ return text; }
    	}
    }
    
    const welcome = html`<p>${t('Welcome')}</p>`;
    
    // We can inspect and modify any inserted variables
    // using the render function's callback.
    // This includes values in nested components.
    await welcome.render(value => {
    	if(value.translatable) {
    		value = translateIntoFrench(value);
    	}
    	return value;
    }) // <p>Bienvenue</p>

    Api

    Dependencies

    None

    Modules

    encode-html-template-tag

    Classes

    Template

    Constants

    htmlTemplate

    Tag function for your html template

    html`There are ${numberOfLights} lights`
    
    joinTemplate

    Creates a Template that joins together an array of values with an optional separator

    html.join([1,2,3,4,5], ' and ')
    
    safeTemplate

    Creates a new Tempalte using a value that won't be encoded when rendered, or passed as a value to another template. Don't use this for unfiltered user input.

    html.safe(markdownToHtml('# Page title\n\n*Hello!*'));
    
    raw

    Alias of html.safe

    elementTemplate

    Helper to create an individual element Void elements are hardcoded and do not accept children.

    encode-html-template-tag

    Template

    Kind: global class

    new Template(literals, variables)

    Create an object representing the template and its values.

    Param Type Description
    literals Array Parts of the template that will not be encoded
    variables Array Parts of the template that will be encoded

    template.with(props) ⇒ Object

    Tag this template with extra properites May be useful in conjunction with certain replacer functions

    Kind: instance method of Template
    Returns: Object - A new object with the passed properties, and the template as the prototype

    Param Type Description
    props Object Properties to assign

    template.generate(replace) ⇒ AsyncIterator

    Yields an async iterator that renders the template to a string. Template variables are handled in the following way: - Strings will have html characters replaced with their html entities - Nested Templates will be rendered - Promises will be resolved - Iterables will be flattened (including arrays, sync and async iterators) A replace function can be passed to alter individual variables before they are encoded. If supplied, this replace function will be passed down to all nested templates.

    Kind: instance method of Template

    Param Type Description
    replace function Function that can be used to replace individual variables

    template.render(replace)

    Render the template to a string. If any of the variables are Promises, return value will be a promise. Otherwise the return value will be a string.

    Kind: instance method of Template

    Param Type Description
    replace function Function that can be used to replace individual variables

    html ⇒ Template

    Tag function for your html template

    html`There are ${numberOfLights} lights`

    Kind: global constant
    Returns: Template - The template object

    join ⇒ Template

    Creates a Template that joins together an array of values with an optional separator

    html.join([1,2,3,4,5], ' and ')

    Kind: global constant

    Param Type Description
    values Array Values to join
    separator String Separator to use, defaults to ,

    safe ⇒ Template

    Creates a new Tempalte using a value that won't be encoded when rendered, or passed as a value to another template. Don't use this for unfiltered user input.

    html.safe(markdownToHtml('# Page title\n\n*Hello!*'));

    Kind: global constant

    Param Type Description
    value String The value to use as a literal

    raw

    Alias of html.safe

    Kind: global constant
    See: html.safe

    element ⇒ Template

    Helper to create an individual element Void elements are hardcoded and do not accept children.

    Kind: global constant

    Param Type Description
    name string The name of the tag to create
    attributes Object The dictionary of attributes for the element. This should be an object whose keys are the attribute names and whose values are the attribute values. Attributes with values that are null, undefined, or false will not be added to the output. Attributes with values that are true will only have the attribute names present in the output, with no value. All other values will be encoded on output.
    ...children children The children to put inside the tag.

    Example

    element('a', { href: 'http://example.com' }, 'Click here for example dot com').render();

    Install

    npm i encode-html-template-tag

    DownloadsWeekly Downloads

    8

    Version

    2.5.0

    License

    ISC

    Unpacked Size

    18.6 kB

    Total Files

    8

    Last publish

    Collaborators

    • paulkiddle