Meteor Capture

Simple modal pattern

Updated to make use of Template.dynamic, which allows passing in a dynamic template

A pattern demonstrating a reusable modal dialog by dynamically rendering a Template using a Session value.

Templates

<body>  
  <p>Body content</p>

  <button class="modal" data-modal-template="modalOne">Modal One</button>
  <button class="modal" data-modal-template="modalTwo">Modal Two</button>

  {{> modal}}
</body>

<template name="modal">  
  {{#if activeModal}}
    <div class="modal">
      {{> Template.dynamic template=activeModal}}
    </div>
  {{/if}}
</template>

<template name="modalOne">  
  <h1>Modal One</h1>
  <p>...</p>
</template>

<template name="modalTwo">  
  <h1>Modal Two</h1>
  <p>...</p>
</template>  

Helpers and event handling

Template.body.events({  
  'click button.modal': function(event, template) {
    var name = template.$(event.target).data('modal-template');
    Session.set('activeModal', name);
  }
});

Template.modal.helpers({  
  activeModal: function() {
    return Session.get('activeModal');
  }
});

Notes

We've created a data-modal-template attribute on our buttons in order to avoid requiring a click handler for each individual button.

For more information on Blaze (Meteor's template rendering engine) and rendering dynamic templates, see https://github.com/meteor/meteor/blob/devel/packages/blaze/README.md

Resources

https://www.discovermeteor.com/blog/blaze-dynamic-template-includes/
Dynamic template includes with Blaze

Example project

https://github.com/dburles/meteor-capture-modal-example
Grab the example project from GitHub.

comments powered by Disqus