2016-10-14 3 views
2

nodejs 응용 프로그램에서 marko 템플릿 엔진을 사용하고 있습니다. 우리는을 만들 어느 때 우리는 3 마르코 레이아웃marko 템플릿에서 전역 변수에 액세스

  1. header.marko
  2. layout.marko
  3. footer.marko

머리글과 바닥 글 레이아웃은 layout.marko

내부 렌더링 한 새로운 마코 페이지 (컨텐츠 페이지) 이것과 같은 레이아웃 마코를 사용합니다

<layout-use template="./../layout.marko"> 

this.body = marko.load("./views/home.marko").stream(data); 

같은210

및로드 마르코 이제 우리는 가변적 세계적으로 액세스하려는. 변수가 username = 'abc'이면 i-e. 이 이름을 헤더, 레이아웃 또는 바닥 글 표식 파일에 액세스하여 표시하려고합니다. 하지만 각 콘텐츠 마코 페이지에 사용자 이름을 전달하고 싶지는 않습니다. i-e 웹 사이트에 100 페이지가 있다면 100 페이지 모두에 사용자 이름을 전달하고 싶지 않습니다. 사용자가 로그인 할 때마다 전역 변수에 사용자 이름을 저장하고 모든 페이지에서이 전역 변수를 사용할 때마다

어떻게 글로벌 변수 기능을 구현할 수 있습니까?

답변

3

속성을 사용하여 모든 템플릿에 데이터 을 노출하는 것처럼 보입니다. 예를 들어

:

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

감사합니다. 그것은 나의 요구를 충족시킨다. –

+0

위대한, 올바른 해결책 +1 –

관련 문제