How to render template with koa?

Member

by addison , in category: Javascript , 9 months ago

How to render template with koa?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by elise_daugherty , 9 months ago

@addison 

To render a template with Koa, you can use a template engine like koa-views. Follow these steps to render a template:

  1. Install the necessary dependencies:
1
npm install koa koa-router koa-views --save


  1. Create a new Koa application in your project's entry point file, such as index.js:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
const Koa = require('koa');
const Router = require('koa-router');
const views = require('koa-views');

const app = new Koa();
const router = new Router();

// Set up views middleware
app.use(views(__dirname + '/views', {
  extension: 'ejs' // Replace with your preferred template engine extension
}));

// Define a route
router.get('/', async (ctx, next) => {
  await ctx.render('index', { title: 'Koa Template' }); // Render 'index' template passing data
});

// Add the router middleware
app.use(router.routes());

// Start the server
app.listen(3000, () => {
  console.log('Server is running on port 3000');
});


  1. Create a views folder in your project's root directory, and inside it, create an index.ejs file with the following content:
1
2
3
4
5
6
7
8
9
<!DOCTYPE html>
<html>
<head>
  <title><%= title %></title>
</head>
<body>
  <h1><%= title %></h1>
</body>
</html>


  1. Start the server by running node index.js.


You should now be able to access the rendered template by visiting http://localhost:3000 in your browser. It will display the title "Koa Template" as defined in the template's render context.