Deno-页面渲染

53次阅读

共计 1236 个字符,预计需要花费 4 分钟才能阅读完成。

Deno 页面渲染


我们一起来完成以下步骤:

  • [X] 1. 首先来了解一下支持页面渲染都有哪些组件:
    Denjucks Ejs Handlebars

    我们今天要学 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})

正文完
 0