Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

easy-template-x

Package Overview
Dependencies
Maintainers
1
Versions
42
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

easy-template-x

Generate docx documents from templates, in Node or in the browser.

  • 0.5.1
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
7.3K
decreased by-7.4%
Maintainers
1
Weekly downloads
 
Created
Source

easy-template-x

Generate docx documents from templates, in Node or in the browser.

CircleCI npm version npm license dependencies dependencies

Prior art and motivation

There are already some very good templating libraries out there, most notably these two:

easy-template-x takes great inspiration from both. It aspires to take the best out of both and to support some usecases that are not supported by either. Specifically, it keeps the ease of use that docxtemplater provides to the end user and adds line break auto insertion which is currently missing there.

Internally it works more like docx-templates than docxtemplater in that sense that it traverses xml documents node by node in a strongly typed manner rather than using a text matching approach.

It was also inspired by docxtemplater modules system and introduces a similar plugins system. The main difference in that area is that the library is fully written in TypeScript and the code base provides a lot of comments and explanation inside, thus making it as easy as possible to write your own custom plugins.

Node Example

import * as fs from 'fs';
import { TemplateHandler } from 'easy-template-x';

// 1. read template file
const templateFile = fs.readFileSync('myTemplate.docx');

// 2. process the template
const data = {
    posts: [
        { author: 'Alon Bar', text: 'Very important\ntext here!' },
        { author: 'Alon Bar', text: 'Forgot to mention that...' }
    ]
};

const handler = new TemplateHandler();
const doc = await handler.process(templateFile, data);

// 3. save output
fs.writeFileSync('myTemplate - output.docx', doc);

Input:

input template

Output:

output document

Browser Example

The following example produces the same output while running in the browser. Notice that the actual template processing (step 2) is exactly the same as in the previous Node example.

import { TemplateHandler } from 'easy-template-x';

// 1. read template file

// (in this example we're loading the template by performing  
//  an AJAX call using the fetch API, another common way to  
//  get your hand on a Blob is to use an HTML File Input)
const response = await fetch('http://somewhere.com/myTemplate.docx');
const templateFile = await response.blob();

// 2. process the template
const data = {
    posts: [
        { author: 'Alon Bar', text: 'Very important\ntext here!' },
        { author: 'Alon Bar', text: 'Forgot to mention that...' }
    ]
};

const handler = new TemplateHandler();
const doc = await handler.process(templateFile, data);

// 3. save output
saveFile('myTemplate - output.docx', doc);

function saveFile(filename, blob) {

    // see: https://stackoverflow.com/questions/19327749/javascript-blob-filename-without-link

    // get downloadable url from the blob
    const blobUrl = URL.createObjectURL(blob);

    // create temp link element
    let link = document.createElement("a");
    link.download = filename;
    link.href = blobUrl;

    // use the link to invoke a download
    document.body.appendChild(link);
    link.click();

    // remove the link
    setTimeout(() => {
        link.remove();
        window.URL.revokeObjectURL(blobUrl);
        link = null;
    }, 0);
}

Writing your own plugins

To write a plugin inherit from the TemplatePlugin class.
The base class provides two methods you can implement and a set of utilities to make it easier to do the actual xml modification.

To better understand the internal structure of Word documents check out this excellent source.

Example plugin implementation (source):

/**
 * A plugin that inserts raw xml to the document.
 */
export class RawXmlPlugin extends TemplatePlugin {

    // Declare your prefix:
    // This plugin replaces tags that starts with a @ sign.
    // For instance {@my-tag}
    public readonly prefixes: TagPrefix[] = [{
        prefix: '@',
        tagType: 'rawXml',
        tagDisposition: TagDisposition.SelfClosed
    }];

    // Plugin logic goes here:
    public simpleTagReplacements(tag: Tag, data: ScopeData): void {

        // Tag.xmlTextNode always reference the actual xml text node.
        // In MS Word each text node is wrapped by a <w:t> node so we retrieve that.
        const wordTextNode = this.utilities.docxParser.containingTextNode(tag.xmlTextNode);

        // Get the value to use from the input data.
        const value = data.getScopeData();
        if (typeof value === 'string') {

            // If it's a string parse it as xml and insert.
            const newNode = this.utilities.xmlParser.parse(value);
            XmlNode.insertBefore(newNode, wordTextNode);
        }

        // Remove the placeholder node.
        // We can be sure that only the placeholder is removed since easy-template-x
        // makes sure that each tag is isolated into it's own separate <w:t> node.
        XmlNode.remove(wordTextNode);
    }
}

API

TODO - Meanwhile, you can checkout the typings file.

Binary Formats

The library supports the following binary formats:

Changelog

The change log can be found here.

Keywords

FAQs

Package last updated on 05 Jun 2019

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc