Search code examples
javascriptjquerytemplatesmeteormeteor-helper

Meteor template helper not working after using iron router


I'm new to Meteor and I just installed iron router to my project. I have this inside my application.js file:

if (Meteor.isClient) {

  Template.nav.helpers({
    isMobile: function(){
      if(isMobile.tablet) {
        return false;
      } else if(isMobile.phone) {
        return true;
      } else {
        return false;
      }
    }
  });

}

The isMobile helper will be used inside my nav template like this:

<template name="nav">
...
  {{#if isMobile}}
    {{> mobile_nav}}
  {{else}}
    {{> desktop_nav}}
  {{/if}}          
...
</template>

What I'm doing here is, I'm loading 2 different sets of navigation. If the user is using desktop or tablet, I'm going to show desktop_nav template and when the user is using phone, I'm going to show mobile_nav.

This is the jQuery plugin that I use inside the isMobile template helper.

Inside my application.html file, I have this:

<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0" />
    <title>Example</title>
</head>

<body>
</body>

<template name="main">
    {{> nav}}   
        {{> yield}}
    {{> footer}}
</template>

And this is my router.js file:

Router.configure({
    layoutTemplate: 'main'
});

Router.route('/', 'home');

Router.route('/about', 'about');

My problem right now is, the isMobile template helper doesn't work. The nav template is loaded but the if else block is not working.

It was working fine before I start using iron router.

What am I missing here?

Note, this is my project structure tree:

├── application.css.scss
├── application.html
├── application.js
├── client
│   ├── javascripts
│   │   ├── isMobile.min.js
│   │   └── router.js
│   ├── stylesheets
│   │   └── ...
│   └── views
│       ├── about.html
│       ├── home.html
│       ├── home.js
│       └── layouts
│           ├── desktop_nav.html
│           ├── footer.html
│           ├── mobile_nav.html
│           └── nav.html
└── public
    ├── fonts
    │   └── ...
    └── images
        └── ...

Solution

  • Problem solved. It was due I'm not initializing the foundation. After I add it, my menu works fine:

    Template.desktop_nav.onRendered(function(){
        $(document).foundation();
    });
    
    Template.mobile_nav.onRendered(function(){
        $(document).foundation();
    });
    

    Another important thing to keep in mind is, $(this).foundation(); doesn't work. Only $(document).foundation(); works. I've no idea what's the differences between $(this) and $(document) in this context.

    Thank Villemh and 3thanZ for the help. I really appreciate it!