流星秀和隐藏模板

jam*_*mes 2 meteor

我正试图找到显示和隐藏模板的流星方式.例如,如果单击主页按钮,则显示主页模板并隐藏所有其他模板.我理解这可以使用会话变量或依赖项,但不能正常工作.

Pep*_*L-G 8

可以通过使用Session变量来实现,但您可能希望使用铁路由器包.

以下是使用Session变量的解决方案:

<body>
    {{#if isPage 'home'}}
        {{> home}}
    {{/if}}
    {{#if isPage 'about'}}
        {{> about}}
    {{/if}}
    <ul>
        <li><button class="clickChangesPage" data-page='home'>Home</button></li>
        <li><button class="clickChangesPage" data-page='about'>About</button></li>
    </ul>
</body>

<template name="home">
    <p>Home!</p>
</template>

<template name="about">
    <p>About!</p>
</template>
Run Code Online (Sandbox Code Playgroud)
if(Meteor.isClient){

    Session.setDefault('page', 'home');

    UI.body.helpers({
        isPage: function(page){
            return Session.equals('page', page)
        }
    })

    UI.body.events({
        'click .clickChangesPage': function(event, template){
            Session.set('page', event.currentTarget.getAttribute('data-page'))
        }
    })

}
Run Code Online (Sandbox Code Playgroud)

2016年火星更新2

正如评论中指出的那样,使用Template.dynamic是一种更好的解决方案.这是使用该代码的代码:

<body>
    {{> Template.dynamic template=currentPage}}
    <ul>
        <li><button class="clickChangesPage" data-page='home'>Home</button></li>
        <li><button class="clickChangesPage" data-page='about'>About</button></li>
    </ul>
</body>

<template name="home">
    <p>Home!</p>
</template>

<template name="about">
    <p>About!</p>
</template>
Run Code Online (Sandbox Code Playgroud)
if(Meteor.isClient){

    Session.setDefault('page', 'home');

    Template.body.helpers({
        currentPage: function(page){
            return Session.get('page')
        }
    })

    Template.body.events({
        'click .clickChangesPage': function(event, template){
            Session.set('page', event.currentTarget.getAttribute('data-page'))
        }
    })

}
Run Code Online (Sandbox Code Playgroud)