0

I have a template that shows a table of posts. The user can edit, add, and delete posts. My site has two different varieties of posts: it has a shared library of posts and each user has posts attached to their profile.

Articles table

My table is the same across the site, but the CRUD operations are different based on whether it's displaying the user's posts or the site's shared post library. For example, when a user adds a post, I need to run Meteor.users.update({_id: [user ID]}, {$push: {'profile.posts': postObject}}). When the site admin adds a post, I need to run Articles.insert(postObject).

What is the best way to do this? I tried passing an argument to my template inclusion (i.e. {{> postsTable source=Articles}}) and testing for that in the event functions, but it seems this replaces the data context which means my template can no longer get to the posts. I also thought about testing the current route and using that to branch the event functions, but that method seems a bit smelly.

Alternatively, I could bind events for the templates that include the table rather than on the table template itself. This is probably the simplest solution, but I would be duplicating a lot of code across those various templates when the only thing that changes is how the resulting data is stored.

raddevon
  • 3,290
  • 4
  • 39
  • 49

1 Answers1

1

I agree that using the current route is an unfortunate mixing of concerns. I'll admit we do that in our app in a few places to get around this exact issue.

If possible, I'd recommend modifying the context to the included postTable template. You have a couple of options:

rename the context and add more variables

{{> postsTable data=this isArticles=true}}

Now your postsTable has access to both the parent context and the isArticles boolean. The only trick is that you'll need to access the context via the data namespace (or whatever you choose to call it) which may seem a little verbose.

extend the context in a helper

Add a helper to the parent template which extends its context like this:

Template.parentTemplate.helpers({
  context: function() {
    var result = _.clone(this);
    result.isArticles = false;
    return result;
  }
});

Then in your template you can do:

{{> postsTable context}}

Your postsTable template will then have the parent context along with the isArticles boolean. This is the technique we prefer whenever possible.

Also see my answer to this question if you'd prefer to do this with a global helper.

Community
  • 1
  • 1
David Weldon
  • 63,632
  • 11
  • 148
  • 146