Pages

Wednesday, May 18, 2016

Learning Meteor.js [Part 21]: Use dynamic templates to swap content on the fly

It is time to return to the main page. The idea is that users will be able to add recipes and/or ingredients to create an order. The UI components that list recipes and ingredients can be reused and what is missing is to dynamically show one or the other list depending on user selection.

The dynamic template feature can be used to build this:
<div class="panel panel-default">
    {{> Template.dynamic template=activeTabTemplate data=tabTemplateData}}
</div>

The two things that the dynamic template needs is the name of the template and an object to use as its data context. These can be supplied by helpers of the page that host the dynamic template:
Template.orderPage.helpers({
    activeTabTemplate() {
        return Template.instance().activeTabTemplate.get();
    },
    tabTemplateData() {
        return {
            enableSelection: false
        }
    }
});

The active template is kept in a ReactiveVar so that when it changes the view reacts by loading the new template in place. The fact that you have to provide data to the dynamic template by a separate object that has be constructed by the helper feels very cumbersome. I would have preferred to pass enableSelection=false when declaring the dynamic template tag, but that is not supported.

Anyway, all that is left is to hook up the handlers when a user clicks on a tab and swap the appropriate template.
Template.orderPage.events({
    'click .component-tab': function(event, template) {
        var $tab = $(event.currentTarget);
        var tabTemplate = $tab.data('template');

        template.activeTabTemplate.set(tabTemplate);
    }
});

You can checkout the source up to this point by using this tag or view the live demo.



No comments:

Post a Comment

Note: Only a member of this blog may post a comment.