Search code examples
javascriptmeteormeteor-blaze

Should I be setting Meteor navigation templates with helpers, or jQuery?


Just a question regarding best practices for Meteor. At the moment I've coded a site with multiple templates active, but disabled with CSS and jQuery. So something like this:

<body>
{{> home }}
{{> about }}
{{> contact }}
</body>

<template name="home"><div id="home">
stuff
</div></template>

In CSS

#about, #contact {display: none}

Then in jQuery I would just change these properties with a click based on whatever page is supposed to be active.

$(document).on('click', '#aboutbutton', function(){
$('#home').fadeOut( set time out and enable about page)
});

Is there anything wrong with doing it this way? Especially since the pages themselves don't need to be reactive, but rather their content?


Solution

  • Is there anything wrong with this? Not sure, but it would be a problem if you later decide to migrate to React, which doesn't work well with JQuery. But for Blaze, this would work.

    The "Meteor" way would be to use helpers and handlebars #if statements.

    <body>
    {{> home }}
    {{> about }}
    {{> contact }}
    </body>
    
    <template name="home">
     {{#if showHome}}
     <div id="home">
      stuff
     </div>
     {{/if}}
    </template>
    

    And then in the .js file, you could have a helper defined as "showHome":

    Template.home.helpers({
      showHome() {
         return someBooleanVariable
      },
    });
    

    However, this makes it hard to do CSS transitions. While there are ways to handle transitions and animations with hooks when Blaze adds or removes templates, it is much easier to handle it in the more traditional way of adding/removing classes.

    <body>
    {{> home }}
    {{> about }}
    {{> contact }}
    </body>
    
    <template name="home">
     <div id="home" class="template {{#if showHome}}showTemplate{{/if}}>
      stuff
     </div>
    </template>
    

    The helper is the same as above, but the stylesheet would be:

    .template {
      transition: opacity 0.3s ease;
      opacity: 0
      /* Some other way of hiding, e.g. offscreen, width: 0 */
    }
    .showTemplate {
      opacity: 1
    }
    

    This gives the advantage of being able to smoothly add or remove the template from the display.