跳到主要内容

koa-views handlebars

一、认识


二、准备


  1. 安装koakoa-routerkoa依赖

    yarn add koa koa-router -S
  2. 安装koa-viewshandlebars 等页面渲染依赖

    yarn add koa-views handlebars -S

三、实现


3.1 根目录/app.js

const Koa = require("koa");
const Views = require("koa-views");
const Path = require("path");
const Router = require("");
require("./views/helpers");

const app = new Koa();
const router = new Router({ prefix: "" });

app.use(
Views(Path.resolve(__dirname, "views"), {
extension: "hbs",
map: { hbs: "handlebars" },
})
);

router.get("/page", async (ctx) => {
const content = {
title: "页面渲染",
a: 1,
b: 2,
c: true,
styles: [
{
url: "http://a.com",
},
{
url: "http://b.com",
},
],
assets: [
{
type: "css",
url: "http://a.com",
},
{
type: "js",
url: "http://b.com",
},
],
imports: {
react: "http://www.baidu.com",
"react-dom": "http://www.baidu.com",
},
};

await ctx.render("index", { ...content });
});

app.use(router.routes());

app.listen(3002, () => {
console.log("页面渲染服务启动成功!");
});

3.2 根目录/views/index.hbs

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{{title}}</title>
{{#each styles}}
<link ref="stylesheet" href="{{this.url}}"></link>
{{/each}}

{{#each assets}}
{{#if (isCss this)}}
<link ref="stylesheet" href="{{this.url}}"></link>
{{else}}
<script type="text/javascript" src="{{this.url}}"></script>
{{/if}}
{{/each}}

<script type="systemjs-importmap">{"imports": {{{stringify imports}}} }</script>

</head>
<body>
<script>
const a = {{a}}
const b = {{b}}
</script>

{{#if c}}
这是一个很寂寞的天,下着有些伤心的雨!
{{/if}}
</body>
</html>

3.3 根目录/views/helpers/index.js

const Fs = require("fs");
const Path = require("path");
const Handlebars = require("handlebars");

const helperPath = Path.resolve(__dirname);
const helperList = Fs.readdirSync(helperPath);
const helperListFilter = helperList.filter((item) => !item.includes("index"));
helperListFilter.forEach((item) => {
const pathObj = Path.parse(item);
const helperItemName = pathObj.name;
const helperItemPath = Path.join(helperPath, item);
const helperItemFunc = require(helperItemPath);
Handlebars.registerHelper(helperItemName, helperItemFunc);
});

3.4 根目录/views/helpers/isCss.js

module.exports = function (value) {
return value.type === "css";
};

3.5 根目录/views/helpers/stringify.js

module.exports = function(value){
if(value == null){
return 'null'
}
return JSON.stringify(value)
}