Koa中配置使用ejs模板引擎

安装插件

npm install koa-views --save
npm install ejs --save
var koa = require('koa');
var Router = require('koa-router');
var views = require('koa-views');
var app = new koa();
var router = new Router();

/**
 * 这样配置后缀名为html
 * app.use(views('./views', {map: {html: 'ejs'}}))
 * */
app.use(views('./views', {
    extension: 'ejs' //配置后缀名为ejs
}))

// 通过中间件为每个ejs引擎赋值
app.use(async (ctx, next) => {
    ctx.state.userName = "张三"
    await next()
})

router.get('/', async (ctx, next) => {
    let title = '你好ejs'
    let list = [1111, 2222, 3333]
    let content = '

标题

'
await ctx.render('index', { title: title, list: list, content: content }); }) app.use(router.routes()) app.use(router.allowedMethods()) app.listen(3000);

<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ejs模板引擎title>
head>

<body>
    
    <%- include ('../public/header.ejs') %>

    
    <h1><%=title %> h1>

    
    <ul>
        <% for( let i in list ) { %>
        <li><%=list[i]%> li>
        <% } %>
    ul>

    
    <%- content %>

    
    <% if(true){ %>
    <div>打印为真div>
    <% }else{ %>
    <div>打印为假div>
    <% } %>

    
    <%=userName %>
body>

html>

你可能感兴趣的:(Koa)