Features
Docs
CLI
Benchmarks
Examples

© 2024 MoroJs

Template Rendering

Render templates with built-in or external engines including Moro, Handlebars, and EJS with support for layouts and helpers.

Basic Template Rendering

MoroJS provides built-in template rendering middleware with support for multiple template engines.

Configure Template Engine

typescript

1import { template } from '@morojs/moro';
2
3// Configure template engine
4app.use(template({
5  views: './views',
6  engine: 'moro', // 'moro' | 'handlebars' | 'ejs'
7  cache: true,
8  defaultLayout: 'layout'
9}));
10
11// Render a template
12app.get('/page', (req, res) => {
13  res.render('index', {
14    title: 'Welcome',
15    user: req.user
16  });
17});

Template Engines

  • moro - Built-in Moro template engine
  • handlebars - Handlebars template engine
  • ejs - EJS template engine
  • • Support for layouts and partials
  • • Custom helpers and filters
  • • Template caching for performance

Template Engines

Using Handlebars

typescript

1import { template } from '@morojs/moro';
2
3// Using Handlebars
4app.use(template({
5  views: './views',
6  engine: 'handlebars',
7  cache: process.env.NODE_ENV === 'production',
8  helpers: {
9    uppercase: (str: string) => str.toUpperCase(),
10    formatDate: (date: Date) => date.toLocaleDateString(),
11    eq: (a: any, b: any) => a === b
12  }
13}));
14
15// Handlebars template (views/index.hbs)
16// <h1>{{title}}</h1>
17// <p>{{user.name}}</p>
18// {{#each items}}
19//   <li>{{name}}</li>
20// {{/each}}

Using EJS

typescript

1import { template } from '@morojs/moro';
2
3// EJS templates
4app.use(template({
5  views: './views',
6  engine: 'ejs',
7  cache: true
8}));
9
10// EJS template (views/index.ejs)
11// <h1><%= title %></h1>
12// <p><%= user.name %></p>
13// <% items.forEach(item => { %>
14//   <li><%= item.name %></li>
15// <% }); %>

Moro Template Syntax

typescript

1// Moro template syntax (views/index.moro)
2<!-- variables -->
3<h1>{{title}}</h1>
4<p>{{user.name}}</p>
5
6<!-- loops -->
7{{#each items}}
8  <li>{{name}}</li>
9{{/each}}
10
11<!-- conditionals -->
12{{#if user}}
13  <p>Welcome, {{user.name}}</p>
14{{else}}
15  <p>Please log in</p>
16{{/if}}
17
18<!-- partials -->
19{{> header}}
20{{> footer}}

Best Practices

Do

  • • Enable template caching in production
  • • Use layouts for consistent structure
  • • Create reusable partials
  • • Escape user input in templates
  • • Use helpers for complex logic
  • • Organize templates by feature

Don't

  • • Put complex logic in templates
  • • Disable caching in production
  • • Trust user input without escaping
  • • Mix template engines
  • • Create deeply nested templates
  • • Skip template validation

Related Features