속성을 사용하여 모든 템플릿에 데이터 을 노출하는 것처럼 보입니다. 예를 들어
:
router.get('/test', function *() {
this.type = 'html'
this.body = marko.load("./views/home.marko")
.stream({
color: 'red',
$global: {
currUser: { id: 2, username: 'hansel' }
}
})
})
그리고 이러한 템플릿 : 작동
// home.marko
<include('./header.marko') />
<h1>color is ${data.color}</h1>
// header.marko
<h2>Header</h2>
<p if(out.global.currUser)>
Logged in as ${out.global.currUser.username}
</p>
<p else>
Not logged in
</p>
.
그러나 분명히 당신이 모든 .stream()
에 $global
을 통과해야하고 싶지 않아, 그래서 하나의 아이디어는 코아 컨텍스트에 저장할 수 있도록 어떤 미들웨어를 여기에 데이터를 연결하고 그것을 전달하는 도우미를 작성하는 것입니다 우리를 위해 템플릿으로
// initialize the object early so other middleware can use it
// and define a helper, this.stream(templatePath, data) that will
// pass $global in for us
router.use(function * (next) {
this.global = {}
this.stream = function (path, data) {
data.$global = this.global
return marko.load(path).stream(data)
}
yield next
})
// here is an example of middleware that might load a current user
// from the database and attach it for all templates to access
router.use(function * (next) {
this.global.currUser = {
id: 2,
username: 'hansel'
}
yield next
})
// now in our route we can call the helper we defined,
// and pass any additional data
router.get('/test', function *() {
this.type = 'html'
this.body = this.stream('./views/home.marko', {
color: red
})
})
그 코드는 내가 위에서 정의 된 템플릿과 함께 작동 : ${out.global.currUser}
이 header.marko에서 액세스 할 수있는, 아직 ${data.color}
는 home.marko에서 액세스 할 수 있습니다.
나는 Marko를 사용한 적이 없지만 때때로 사용한다고 생각 했으므로 질문을 본 후 문서를 읽을만큼 궁금합니다. 나는 이 <layout-use>
의 작동 방식을 파악하는 것처럼 느껴지지 않았으므로 대신 <include>
을 사용했습니다.
감사합니다. 그것은 나의 요구를 충족시킨다. –
위대한, 올바른 해결책 +1 –