Meteor Template States
Template states for Blaze. Forked from gwendall:template-states.
Features and differences to gwendall:template-states
Features
- provide state access across all Templates in the same easy way like the original
- let the developer decide about the helper access
- Minimalistic, clean and tested codebase
Differences are
- The state object is a directly references
ReactiveDict, which is why access is determined by the ReactiveDict API (set/get). - There is not a helper created for every variable, that is pushed/removed to the state. Accessing via SpaceBars acts through the
statehelper (see examples). There are some cases, where you might not directly access the variable but name a helper just like the variable but process the value before returning it (e.g. decoration, proxy object etc.). - There is a shortcut for
Template.instance().state.<get/set>to be accessed in helpers.
Changelog
0.2.2
- Tests / coverage improved
- Template.toggle added (in addition to instance.toggle)
- refactored code style to standardjs
Installation
meteor add jkuester:template-states
Methods
Use with TemplateInstance
set / get
instance.state.set(key, value) - Sets a template state variable by key.
instance.state.get(key) - Gets a template state variable by key.
Example
Declare your states in onCreated hooks
1Template.post.onCreated(function() { 2 const instance = this; 3 instance.state.set('loading', false); 4})
The states are then available in your templates.
1Template.post.events({ 2 'submit form': function(event, instance) { 3 instance.state.get('loading', true); 4 Meteor.call('post.create', { ... }, function(err, res) { 5 instance.state('loading', false); 6 // Do something else 7 }); 8 } 9})
toggle
instance.toggle(key) - Toggles a boolean key between false and true (switches value to !value).
Note: if you apply this on non-boolean state variables, they become boolean.
Use with Template
Template.setState(key, value) - Sets the state on the current Template's instance.
Template.getState(key) - Returns the state on the current Template's instance.
Note: This calls Template.instance() and accesses the current instance's state.
Example
Declare your states in onCreated hooks
1Template.post.onCreated(function() { 2 const instance = this; 3 instance.state.set('loading', false); 4})
The states are then available in your helpers.
1Template.post.helpers({ 2 loadComplete() { 3 const loading = Template.getState('loading'); 4 // maybe check other things here.... 5 return !loading; 6 } 7})
Use with Spacebars
Declare your states in onCreated hooks
1Template.post.onCreated(function() { 2 const instance = this; 3 instance.state.set('loading', false); 4})
Then use your state variable in your html content like this:
1 <template name="post"> 2 {{#if (state 'loading')}} 3 Loading... 4 {{/if}} 5 </template>