나는이 기본 koa v2
을 사용하여 템플릿 리터럴을보기 엔진으로 구현하려고합니다. ./views/index.js
에서 state
의 값을 app.js
에서 어떻게 채울 수 있습니까?CommonJS 모듈에서 객체의 값을 수정할 수없는 이유는 무엇입니까?
내 문제는 내가의 내가 <title></title>
태그 사이 title
개체 값을 포함 할 가정 해 봅시다 .views/partials/mainTop.js
파일로 다운 ctx.body = index.render({})
에서 모든 방법을 개체 값을 밀어 할 것입니다. 이를 달성하기위한 방법이 있습니까 .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
./views/partials/mainBottom.js
module.exports =() => {
return `
...
</body>
</html>
`;
}
불분명 함. 어디에서나 접근 할 수있는 메서드를 정의하여 값을 반환하거나 최후의 수단으로 전역을 사용할 수 있습니다. – dandavis
'mainTop'이 문자열 속성이있는 객체로 정의 된 이유는 무엇입니까? 'mainBottom'은 문자열을 반환하는 함수로 정의되어 있습니다. – Bergi