【发布时间】:2017-02-02 07:36:30
【问题描述】:
我有这个基本的koa v2 应用程序,我在其中尝试将模板文字实现为查看引擎。在./views/index.js 中,如何从app.js 填充state 的值?
我的问题是我想将对象值从ctx.body = index.render({}) 一直推送到.views/partials/mainTop.js 文件,假设我想在<title></title> 标签之间包含title 对象值。有没有办法在app.js 中不需要.views/partials/mainTop.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>
`;
}
【问题讨论】:
-
不清楚。你可以定义一个任何地方都可以访问的方法来返回值,或者最后的手段,使用一个全局的。
-
我想知道为什么
mainTop被定义为具有字符串属性的对象,而mainBottom被定义为返回字符串的函数。
标签: javascript node.js commonjs es6-modules template-literals