乐闻世界logo
搜索文章和话题

How to use EJS template engine with NestJS?

1个答案

1

Using the EJS template engine with NestJS is not a common practice, as NestJS is primarily designed for building APIs and aligns better with decoupled frontend-backend architectures. However, if you need to use EJS as a server-side template engine to render HTML within NestJS, you can follow these steps:

  1. Install the required dependencies: First, install the ejs package as a project dependency.

    bash
    npm install ejs
  2. Configure NestJS to use EJS: In your NestJS application, configure the ViewEngine to use EJS. This is typically done in the main.ts file.

    typescript
    import { NestFactory } from '@nestjs/core'; import { AppModule } from './app.module'; import * as express from 'express'; async function bootstrap() { const app = await NestFactory.create(AppModule); app.use(express.static('public')); // If you have static files (e.g., CSS, JavaScript, images). app.setViewEngine('ejs'); // Set EJS as the template engine. await app.listen(3000); } bootstrap();
  3. Create EJS template files: In your project directory, create a folder to store EJS template files (e.g., views), and create EJS template files within it (e.g., index.ejs).

    shell
    /src /views index.ejs

    In the index.ejs file, you can write HTML code and use EJS template syntax:

    html
    <!DOCTYPE html> <html> <head> <title><%= title %></title> </head> <body> <h1><%= message %></h1> </body> </html>
  4. Render EJS templates in controllers: Next, in your controllers, you can use the @Render decorator or the res.render method to render EJS templates and send responses.

    typescript
    import { Controller, Get, Render } from '@nestjs/common'; @Controller() export class AppController { @Get() @Render('index') // Points to the index.ejs file in the views folder. root() { return { title: 'Hello World', message: 'Welcome to NestJS with EJS!' }; } }

These steps provide a basic guide on integrating the EJS template engine into a NestJS application. It's important to note that this integration is typically used for server-side rendering (SSR), which is becoming less common in modern web development due to frontend frameworks like React, Angular, and Vue handling the view layer. If your NestJS application needs to work with these frontend frameworks, you might prefer to build a pure API service rather than using EJS to render HTML.

2024年6月29日 12:07 回复

你的答案