Search code examples
jquerymeteoriron-router

Access user profile information for onRender template using iron-router


I'm trying to access user data in code on the client for my user profile pages onRendered.

I have this in my client:

 Template.profile.onRendered(function () {
      $('#qrblock').qrcode({text: <I want to show user's qrUrl here>});
    });

Here is the user schema when a user is created:

Accounts.createUser({
    username: username,
    emails: [
      { address: email, verified: false }
    ],
    password: password,
    createdAt: new Date(),
    profile:{
      firstName: firstName,
      lastName: lastName,
    },
    qrUrl: 'test.meteor.com/@' + username
  },
...
...
...

Here is my template:

<template name="profile">
<div class="container-fluid">
    Username:   {{username}}<br />
    {{#with profile}}
        Profile name: {{firstName}} {{lastName}}
    {{/with}}
    <div id="qrblock"></div>
</div>
</template>

Here's my router and controller:

Router.route('/@:username', {
  name: 'profile',
  controller: 'ProfileController'
});

ProfileController = RouteController.extend({
  template: 'profile',
  waitOn: function() {
    return Meteor.subscribe('userProfile', this.params.username);
  },
  data: function() {
    var username = Router.current().params.username;
    return Meteor.users.findOne({
      username: username
    });
  }
})

I'm not very great with the meteor routing stuff so that's confusing me when it comes to accessing user data for a specific profile page. I hope what I'm trying to do is even possible.

How do I use user data in my profile Template onRendered function?


Solution

  • You can access the template instance in your Template.myTemplate.onCreated, Template.myTemplate.onRendered and Template.myTemplate.onDestroyed function with this.

    If you want to access the data context, you can use this.data:

    Template.profile.onRendered(function() {
        $('#qrblock').qrcode({
            text: this.data.qrUrl
        });
    });