Flowrouter/Blaze: can template helpers be used to change a parent's content?


#1

Hey guys,

example: a page has one layout with one navigation bar, using Flowrouter for the routing (also using Blaze).

I now want to change the content of the main layout dynamically with Template helpers of the subroutes.

Say I click on link1, then the link1 template will load. Inside the link1 template I have a template helper which changes the content of a div which is only included in the main layout.

Like this:
grafik

<template name="myMainLayout">
<div>
    <div class="myDiv">{{dynamicText}}</div>
	<nav>
	    <ul class="nav">
	        <li><a href="{{pathFor 'link1.route'}}">Link 1<a></li>
                <li><a href="{{pathFor 'link2.route'}}">Link 2<a></li>
                <li><a href="{{pathFor 'link3.route'}}">Link 3<a></li>
                <li><a href="{{pathFor 'link4.route'}}">Link 4<a></li>
            </ul>
        </nav>
     {{> Template.dynamic template=main}}
</div>

So when I now have a template for Link 1, can I define the helper for {{dynamicText}}?

If that is not possible, then I could only think of doing the logic inside the myMainLayout template helper, in which I just check the current path and based on the path I change the value of dynamicText. What do you think?

Thanks in advance!


#2

The simplest way is to make dynamicText a ReactiveVar and pass a reference to the template being rendered.
Then the template can call this.data.dynamicText.set('foobar') to update the var on the parent.

Pass data in your template with {{> Template.dynamic template=main data=getData }} in your template and this in your js

Template.myMainLayout.onCreated(function () {
  this.data.dynamicText = new ReactiveVar('');
});
Template.myMainLayout.helpers({
  getData: function() {
    return { dynamicText: this.dynamicText }
  }
});

You may need to add ReactiveVar to your project meteor add reactive-var


#3

Well, the simplest way IMHO is to install ViewModel and share the div content. :slight_smile: