@addison
To render a template with Koa, you can use a template engine like koa-views
. Follow these steps to render a template:
1
|
npm install koa koa-router koa-views --save |
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 2 3 4 5 6 7 8 9 |
<!DOCTYPE html> <html> <head> <title><%= title %></title> </head> <body> <h1><%= title %></h1> </body> </html> |
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.