Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

0727 #19

Open
LeungKaMing opened this issue Jul 27, 2017 · 0 comments
Open

0727 #19

LeungKaMing opened this issue Jul 27, 2017 · 0 comments

Comments

@LeungKaMing
Copy link
Owner

LeungKaMing commented Jul 27, 2017

话题

提到NodeJS,肯定要说说模板引擎。以下先举例ejs,相关的还有handlebars。
Koa使用模板必须经过模板引擎,所以要安装依赖~

# 安装koa模板使用中间件
npm install --save koa-views

# 安装ejs模板引擎
npm install --save ejs

一般将模板放在view目录下面

// ./view/index.ejs
<!DOCTYPE html>
<html>
<head>
    <title><%= title %></title>
</head>
<body>
    <h1><%= title %></h1>
    <p>EJS Welcome to <%= title %></p>
</body>
</html>
// index.js
const Koa = require('koa')
const views = require('koa-views')
const path = require('path')
const app = new Koa()

// 加载模板引擎
app.use(views(path.join(__dirname, './view'), {
  extension: 'ejs'
}))

app.use( async ( ctx ) => {
  let title = 'hello koa2'
  // 用于渲染模板引擎,第一个参数是表示模板名字;第二个参数是可选选项,用于传去模板对应位置<%= %>
  await ctx.render('index', {
    title
  })
})

app.listen(3000)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant