Reputation: 1423
I have a menu bar and I have 3 different pages. Depending on which page I'm at, the contents inside the menu bar will differ. Since the contents are different, I've created 3 different templates. However, the structure of the menu bar is the same except for the contents so I find that I have a lot of duplicate code. Is there a way to have only one template and still populate the content inside the menu bar differently depending on which page you're on?
Setting the contents of template 1 (I do the same thing for the other two templates but only the name differs):
Template.pictureMenu.contents = function(){
...
};
Actual template (I do the same thing for the other two templates but only the name differs):
<template name="pictureMenu">
<div class="navbar">
<div class="navbar-inner">
<div class="container">
<a class="btn btn-navbar" data-target=".nav-collapse" data-toggle="collapse"> <span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</a>
<a class="brand" href="#">Media Menu</a>
<div class="nav-collapse collapse">
<ul class="nav">
<li>
<a href="#">Upload</a>
</li>
<li class="dropdown">
<a class="dropdown-toggle" data-toggle="dropdown" href="#">Playlists<b class="caret"></b></a>
<ul class="dropdown-menu">
**{{#each contents}} <!-- This is the only thing that changes-->
<li>
<a href="#" class="viewPlaylist">{{this}}</a>
</li>
{{/each}}**
</ul>
</li>
<li>
<a href="#">Share</a>
</li>
</ul>
<form action class="navbar-search pull-right">
<input class="search-query span2" placeholder="Search" type="text">
</form>
</div>
</div>
</div>
</div>
</template>
How would I reduce it to 1 template and still have different contents passed to it?
Upvotes: 2
Views: 318
Reputation: 12231
You can rename your template to just "menu" and then insert specific content at the location where the content varies:
<template name="menu">
...
<ul class="dropdown-menu">
{{#each currentMenu}}
<li>{{itemName}}</li>
{{/each}}
</ul>
...
</template>
Template.menu.currentMenu = function() {
return Session.get("currentMenu");
}
Then when you change locations in your site and you want to update the menu, just update the session:
var newMenu = [{itemName: "item1"}, {itemName: "item2"}, {itemName: "etc"}];
Session.set("currentMenu", newMenu);
Upvotes: 1