Koa2中使用art-template模板和静态资源托管

Koa2中使用art-template模板

1.koa2使用art-template模板引擎

// 1.需要安装koa-art-template和art-template模板

npm i koa-art-template

npm i art-template


// 引入koa-art-template

const render = require('koa-art-template')


// 在中间件中配置

render(app, {
    root: path.join(__dirname, 'template'),  // 视图的位置
    extname: '.html', // 文件的后缀名字
    debug: process.env.NODE_ENV !== 'production'
})


// 在路由中使用

router.get('/get', async ctx => {

    let name = "小美"

    let str = '<h1>您好,我是一个h1</h1>'
    
    // 通过ctx.render()来使用第一个参数是.html文件的前缀,第二个参数是一个对象,用来像模板中传递变量参数

    await ctx.render('index', {
        name,
        str
    })
})

2.静态资源的托管

// 安装静态资源托管的包

npm i koa-static


// 引入静态资源托管的包

const static = require('koa-static')


// 直接使用,指定要托管的目录

app.use(static(path.join(__dirname, 'public')))

猜你喜欢

转载自www.cnblogs.com/zxuedong/p/12579160.html
今日推荐