#Deno 页面渲染#
视频讲解 https://www.bilibili.com/video/BV1BT4y1E7Nh/?p=2
我们一起来完成以下步骤:
-
[X] 1. 首先来了解一下支持页面渲染都有哪些组件:
NO Name Star A Denjucks 13 B Ejs 4.5K C Handlebars 15.4K 我们今天要学Ejs模板引擎入门。其他两个如法炮制
-
[X] 2. 创建Controller
-
[X] 3. 创建Router
-
[X] 3. 创建页面index.ejs
-
[x] 4. 创建主应用文件main.ts
-
[X] 5. 测试
#controllers/controller.ts
const { cwd } = Deno;
class Controller {
static async getData(ctx: any){
//cwd获取当前工程目录
//注意 ' !== `
ctx.render(`${cwd()}/views/index.ejs`,{
title:"Testing",
data:{name:"deepincoding.com"}
});
}
}
export default Controller;
#routers/index.ts
import { Router } from "https://deno.land/x/oak/mod.ts";
import Controller from "../controllers/Controller.ts";
const router = new Router();
router.get("/",Controller.getData);
export default router;
#views/index.ejs
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title><%= title %></title>
</head>
<body>
<h2>Hello <%= data.name %></h2>
</body>
</html>
#main.ts
import { Application } from "https://deno.land/x/oak/mod.ts"
import {viewEngine,engineFactory,adapterFactory} from "https://deno.land/x/view_engine/mod.ts";
import router from "./routers/index.ts";
const ejsEngine = engineFactory.getEjsEngine();
const oakAdapter = adapterFactory.getOakAdapter();
const app = new Application();
app.use(viewEngine(oakAdapter,ejsEngine));
app.use(router.routes());
app.use(router.allowedMethods());
await app.listen({port: 8000 })