Neglected Pizza Money

    @tsed/engines
    TypeScript icon, indicating that this package has built-in type declarations

    7.7.0 • Public • Published

    Ts.ED logo

    Ts.ED Engines

    Build & Release semantic-release code style: prettier github opencollective

    Website   •   Templating with Ts.ED   •   Slack   •   Twitter

    Template engine consolidation library (inspired from consolidate) written in TypeScript.

    Feature

    • Support multiple engine library,
    • Extendable - You can register your own engine,
    • Configurable,
    • Agnostic from Express/Koa (but compatible with Express).

    Installation

    npm install @tsed/engines

    Supported template engines

    Some package has the same key name, @tsed/engines will load them according to the order number. For example with dust, @tsed/engines will try to use in this order: dustjs-helpers and dustjs-linkedin. If dustjs-helpers is installed, dustjs-linkedin will not be used by consolidate.

    Name Package Name / Order Website / State
    atpl npm install atpl -
    bracket npm install bracket-template -
    dot npm install dot (website)
    dust npm install dustjs-helpers (2) or
    npm install dustjs-linkedin (3)
    (website)
    ect npm install ect (website)
    ejs npm install ejs (website)
    hamlet npm install hamlet -
    hamljs npm install hamljs -
    haml-coffee npm install haml-coffee -
    handlebars npm install handlebars (website)
    hogan npm install hogan.js (website)
    htmling npm install htmling -
    jazz npm install jazz -
    just npm install just -
    liquor npm install liquor -
    lodash npm install lodash (website)
    marko npm install marko (website)
    mote npm install mote (website)
    mustache npm install mustache -
    nunjucks npm install nunjucks (website)
    plates npm install plates -
    pug npm install pug (website) / (formerly jade)
    ractive npm install ractive -
    react npm install react -
    slm npm install slm -
    squirrelly npm install squirrelly (website)
    swig npm install swig-templates (2) -
    teacup npm install teacup -
    templayed npm install templayed (website)
    toffee npm install toffee -
    twig npm install twig (wiki)
    twing npm install twing (website)
    underscore npm install underscore (website)
    vash npm install vash -
    velocityjs BETA (website)
    walrus npm install walrus (website)
    whiskers npm install whiskers -
    vue npm install vue vue-pronto (website)

    NOTE: you must still install the engines you wish to use, add them to your package.json dependencies.

    API

    You can get an engine by using engines:

    import {getEngine} from "@tsed/engines";
    
    getEngine("swig")
      .renderFile({user: "tobi"})
      .then((html) => {
        console.log(html);
      });

    Or render directly a template:

    import {getEngine} from "@tsed/engines";
    
    getEngine("ejs")
      .render("<p><%= user.name %></p>")
      .then((html) => {
        console.log(html);
      });

    Caching

    To enable caching simply pass { cache: true }. EnginesContainer may use this option to cache things reading the file contents, compiled Functions etc. EnginesContainer which do not support this may simply ignore it. All engines that consolidate.js implements I/O for will cache the file contents, ideal for production environments. When using @tsed/engines directly: getEngine('swig').renderFile('views/page.html', { user: 'tobi', cache: true });

    Using supported Express versions: app.locals.cache = true or set NODE_ENV to 'production' and Express will do this for you.

    Express example

    @tsed/engines can be used with Express as following:

    import express from "express";
    import {getEngine} from "@tsed/engines";
    
    // assign the swig engine to .html files
    app.engine("html", getEngine("swig"));
    
    // set .html as the default extension
    app.set("view engine", "html");
    app.set("views", __dirname + "/views");
    
    var users = [];
    users.push({name: "tobi"});
    users.push({name: "loki"});
    users.push({name: "jane"});
    
    app.get("/", function (req, res) {
      res.render("index", {
        title: "Ts.ED EnginesContainer"
      });
    });
    
    app.get("/users", function (req, res) {
      res.render("users", {
        title: "Users",
        users: users
      });
    });
    
    app.listen(3000);
    console.log("Express server listening on port 3000");

    Koa

    @tsed/engines can be used with Koa as following:

    import {getEngines} from "./getEngines";
    
    var views = require("koa-views");
    
    const render = views(__dirname + "/views", {
      engineSource: getEngines(),
      map: {
        html: "underscore"
      }
    });
    
    // Must be used before any router is used
    app.use(render);
    // OR Expand by app.context
    // No order restrictions
    // app.context.render = render()
    
    app.use(async function (ctx) {
      ctx.state = {
        session: this.session,
        title: "app"
      };
    
      await ctx.render("user", {
        user: "John"
      });
    });

    Template Engine Instances

    Template engines are exposed via the requires object, but they are not instantiated until you've called the getEngine(engine).render() method. You can instantiate them manually beforehand if you want to add filters, globals, mixins, or other engine features.

    import {requires} from "consolidate";
    import nunjucks from "nunjucks";
    
    // add nunjucks to requires so filters can be
    // added and the same instance will be used inside the render method
    requires.set("nunjucks", nunjucks.configure());
    
    requires.get("nunjucks").addFilter("foo", () => {
      return "bar";
    });

    Implement your own engine

    @tsed/engines let you register your own engine by using the @ViewEngine decorator. Here an is example of pug engine implementation:

    import {Engine, ViewEngine} from "@tsed/engines";
    
    @ViewEngine("pug", {
      requires: ["pug", "then-pug"] // multiple require is possible. Ts.ED will use the first module resolved from node_modules
    })
    export class PugEngine extends Engine {
      protected $compile(template: string, options: any) {
        return this.engine.compile(template, options);
      }
    
      protected async $compileFile(file: string, options: any) {
        return this.engine.compileFile(file, options);
      }
    }

    See more examples in packages/engines/src/components directory.

    Override engine

    import {PugEngine} from "@tsed/engines";
    
    @ViewEngine("pug", {
      requires: ["pug", "then-pug"] // multiple require is possible. Ts.ED will use the first module resolved from node_modules
    })
    export class CustomePugEngine extends PugEngine {
      protected $compile(template: string, options: any) {
        return super.$compile(template, options);
      }
    
      protected async $compileFile(file: string, options: any) {
        return super.$compileFile(file, options);
      }
    }

    Notes

    • If you're using Nunjucks, please take a look at the exports.nunjucks.render function in packages/engines/src/components/NunjuncksEngine.ts. You can pass your own engine/environment via options.nunjucksEnv, or if you want to support Express you can pass options.settings.views, or if you have another use case, pass options.nunjucks (see the code for more insight).
    • You can pass partials with options.partials
    • For using template inheritance with nunjucks, you can pass a loader with options.loader.
    • React To render content into a html base template (eg. index.html of your React app), pass the path of the template with options.base.

    Contributors

    Please read contributing guidelines here

    Backers

    Thank you to all our backers! 🙏 [Become a backer]

    Sponsors

    Support this project by becoming a sponsor. Your logo will show up here with a link to your website. [Become a sponsor]

    License

    The MIT License (MIT)

    Copyright (c) 2016 - 2021 Romain Lenzotti

    Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

    The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

    Install

    npm i @tsed/engines

    DownloadsWeekly Downloads

    4,725

    Version

    7.7.0

    License

    MIT

    Unpacked Size

    300 kB

    Total Files

    222

    Last publish

    Collaborators

    • romakita