我有这个基本koa v2
的应用程序,我尝试在其中将模板文字实现为查看引擎。./views/index.js
如何填充fromstate
的值app.js
?
我的问题是我想将对象值从ctx.body = index.render({})
一路向下推送到.views/partials/mainTop.js
文件,假设我想在标签title
之间包含对象值。<title></title>
有没有办法在不需要.views/partials/mainTop.js
in的情况下实现这一目标app.js
?如果它是把手或 nunjucks 模板,我想用模板文字实现类似的东西。
./app.js
const index = require('./views/index');
const app = new Koa();
app.use(ctx => {
index.state = {
foo: 'bar',
};
ctx.body = index.render({
title: 'Template Literals',
description: 'Vanilla JS rendering',
});
});
app.listen(3000);
./views/index.js
const main = require('./layouts/main');
let state = {};
module.exports.state = state;
console.log(state); // returning an {} empty object, expected => { foo: "bar" }
module.exports.render = (obj) => {
return main.render(`
<p>Hello world! This is HTML5 Boilerplate.</p>
${JSON.stringify(obj, null, 4)}}
${obj.title}
`);
};
./views/layouts/main.js
const mainTop = require('../partials/mainTop');
const mainBottom = require('../partials/mainBottom');
module.exports.render = (content) => {
return `
${mainTop.render}
${content}
${mainBottom()}
`;
}
./views/partials/mainTop.js
const render = `
<!doctype html>
<html class="no-js" lang="">
<head>
<title></title>
...
`;
module.exports.render = render;
./views/partials/mainBottom.js
module.exports = () => {
return `
...
</body>
</html>
`;
}