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

@tsed/engines

Package Overview
Dependencies
Maintainers
1
Versions
391
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@tsed/engines

Template engines library. Provide an API to adding custom engines from decorators.

  • 7.71.1
  • Source
  • npm
  • Socket score

Version published
Maintainers
1
Created
Source

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.

NamePackage Name / OrderWebsite / State
atplnpm install atpl-
bracketnpm install bracket-template-
dotnpm install dot(website)
dustnpm install dustjs-helpers (2) or
npm install dustjs-linkedin (3)
(website)
ectnpm install ect(website)
ejsnpm install ejs(website)
hamletnpm install hamlet-
hamljsnpm install hamljs-
haml-coffeenpm install haml-coffee-
handlebarsnpm install handlebars(website)
hogannpm install hogan.js(website)
htmlingnpm install htmling-
jazznpm install jazz-
justnpm install just-
liquornpm install liquor-
lodashnpm install lodash(website)
markonpm install marko(website)
motenpm install mote(website)
mustachenpm install mustache-
nunjucksnpm install nunjucks(website)
platesnpm install plates-
pugnpm install pug(website) / (formerly jade)
ractivenpm install ractive-
reactnpm install react-
slmnpm install slm-
squirrellynpm install squirrelly(website)
swignpm install swig-templates (2)-
teacupnpm install teacup-
templayednpm install templayed(website)
twignpm install twig(wiki)
twingnpm install twing(website)
underscorenpm install underscore(website)
vashnpm install vash-
velocityjsBETA(website)
walrusnpm install walrus(website)
whiskersnpm install whiskers-

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.js";

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.

Keywords

FAQs

Package last updated on 08 Jun 2024

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