DEV Community

Cover image for How to Use Multiple Template Engines within One Class?
NotFound404
NotFound404

Posted on

How to Use Multiple Template Engines within One Class?

Normally we use one template engine for one project.
But it is possible to use multiple template engines within one project. You can initialise many templates and use them separately.

Image description

With Aex, you can do it much simpler.

You can initialize your template engine within an init function, and pass related parameters to the init function.
Or you can wrap this init function into a shared function in a separated file.

In aex, it provides a decorator called template to help you to prepare a template for your web handler.

You can check here for more details on how to use the template decorator.

The following is how it looks like with multiple template engines, template engine nunjucks and pug are used here.

class Template {
  @http("/one")
  @template(
    // init function
    (path) => {
    const loader = new nunjucks.FileSystemLoader([path], {});
    const env = new nunjucks.Environment(loader, {
      autoescape: false,
    });
    return env;
  }, resolve(__dirname, "./views"))
  public async name(_: any, res: any) {
    // access using res.render
    res.render("index.html", { hello: "Hello" });
  }

  @http("/pug")
  @template((path) => {
    const engine: any = {};

    // engine render function rewrite
    engine.render = function (name: string, data: any) {
      let file = name;
      if (!existsSync(name)) {
        if (!existsSync(resolve(path, name))) {
          throw new Error("File Not Found: " + resolve(path, name));
        } else {
          file = resolve(path, name);
        }
      }
      return pug.renderFile(file, data);
    };
    return engine;
  }, resolve(__dirname, "./views"))
  public async name2(_: any, res: any, scope: any) {
    // access using scope.engine
    res.end(scope.engine.render("index.pug", { hello: "Hello" }));
  }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
jwhenry3 profile image
Justin Henry

This seems like it would be best used when migrating legacy applications using specific template engines where the standard has shifted and now you need to use a new template engine.

I could also see a use case when a template engine handles PDF better than HTML and vice versa. Outside of that, I'd imagine it would be best to keep to 1 engine.