Templating Engine
Novaxjs2 includes a powerful templating engine with conditionals, loops, and variable interpolation.
Setting Up Views
// Configure view engine
app.setViewEngine('novax', {
viewsPath: './views' // optional, defaults to './views'
});
Basic Template
Create a file views/home.html
:
<!DOCTYPE html>
<html>
<head>
<title>{{ title }}</title>
</head>
<body>
<h1>{{ heading }}</h1>
{{#if user}}
<p>Welcome back, {{ user.name }}!</p>
{{#else}}
<p>Please log in</p>
{{/if}}
{{#each items}}
<div class="item">
<h3>{{ name }}</h3>
<p>Price: ${{ price }}</p>
</div>
{{/each}}
</body>
</html>
Rendering Templates
app.get('/', async (req, res) => {
const data = {
title: 'Home Page',
heading: 'Welcome to our site',
user: { name: 'John Doe' },
items: [
{ name: 'Product 1', price: 19.99 },
{ name: 'Product 2', price: 29.99 }
]
};
return await app.render('home', data);
});
Template Features
Feature | Syntax | Description |
---|---|---|
Variables | {{ variable }} |
Output variable value |
Conditionals | {{#if condition}}...{{/if}} |
Conditional rendering |
Else / Else If | {{#else}}...{{/else}} {{#elif condition}}...{{/elif}} |
Else clause for conditionals |
Loops | {{#each array}}...{{/each}} |
Iterate over arrays |
Nested | {{#each}}{{#if}}...{{/if}}{{/each}} |
Nested conditionals and loops |