How to use template engine without using any controller in standalone NestJS Application?

1.5k views Asked by At

I'm trying to create telegram chatbot application using nestjs-telegraf

And then I've idea to use template engine like what has been taught from here, to render the reply message for each message has been received.

But, I don't find any way how to do that. All I have got is everyone using @Res res parameter in their method, and then just return res.render(...)

Is there any way to that?

I don't want to manually format the reply message by using ` and using string interpolation.

2

There are 2 answers

3
Juan Rambal On

Choose View Engine

First of all, you have to choose a view engine, this will be in charge of rendering the template and doing the necessary interpolation.

You can check these view engines:

Handlebars: https://handlebarsjs.com/

Pug: https://pugjs.org/api/getting-started.html

Configure the app

Then, you have to create a view and public folders, usually this folder is located in the root layer of your project directory.

View and public folders

Then, add in your main.ts the following code

Set public and views on app

This will tell express where are the views (templates) and the public (Css or Js files, etc.) files located.

Set hbs engine

Add the setViewEngine method indicating the view engine, in this case is handlebars (hbs).

Create template files

With this configuration you can start creating your templates files, let's see the example on the docs.

handlebars file

He created a file in the views folder called index.hbs and wrote that code, handlebars is basically html and the curly braces indicates that you can put a value on that space.

Render the file

The last thing to do is on your controller, create a Get method, add the render decorator and put the name of the view file, then return an object containing the values that you want to interpolate on the template and handlebars will do the rest.

Render method

If you need more info or have some questions you can leave me a comment :)

0
Wladimir On

I think you can use a callback parameter from res.render(), like this:

import { Response } from 'express';
import { Post, Controller, Res } from '@nestjs/common';

@Controller()
export class MyController {
  @Get()
  root(@Res() response: Response) {
    await response.render(
        'index',
        { variable: 'My variable' },
        function (error, html) {
            console.log(html)
        }
    );
    // return any JSON you want
    return response.send({message: 'You HTML was proceed'})
  }
}