dburles:spacebars-tohtml

v1.0.1Published 9 years ago

This package has not had recent updates. Please investigate it's current state before committing to using it in your project.

Meteor Spacebars.toHTML

A simple helper function to assist with rendering spacebars to HTML. Works on both the server and the client.

Installation

$ meteor add dburles:spacebars-tohtml

API

Super basic example

1Spacebars.toHTML({ name: 'foo' }, '<p>Hello {{name}}</p>');

Any helpers defined with Template.registerHelper will be rendered just like usual. If you're on the server you'll need to make sure they're not just defined on the client so it can see them.

Rendering templates on the server

We can render templates on the server by creating files within the private directory.

For example, we could create private/example.html and its contents might look like:

1<html>
2<head>
3  <title>Example</title>
4</head>
5<body>
6  <h1>Example</h1>
7  
8  <p>Hello {{name}} this is just an example!</p>
9</body>
10</html>

We can then render it using Meteor's Assets API

1var html = Spacebars.toHTML({ name: 'foo' }, Assets.getText('example.html'));

This is very useful for sending HTML emails.

Iron Router

We can also serve templates using Iron Router's server side routes.

Here's a simple example:

1Router.route('/test', function() {
2  // This could also come from a Collection
3  var data = { name: 'foo' };
4  
5  this.response.writeHead(200, { 'Content-Type': 'text/html' });
6  this.response.end(Spacebars.toHTML(data, Assets.getText('example.html')));
7}, { where: 'server' });

Template inclusion

Server side only

Currently there's no way to pull in templates using the {{> inclusion}} operator, though we can create our own helper to do much the same thing.

1Template.registerHelper('include', function(template, data) {
2  data = data || {};
3  return Spacebars.toHTML(data, Assets.getText(template));
4});

and within our template, for example:

1<nav>
2  {{{include 'navigation.html'}}}
3</nav>
4...

We can also pass in an optional data context:

1<nav>
2  {{{include 'navigation.html' navItems}}}
3</nav>
4...

Note that we use the triple-stash here so the HTML is not escaped.

License

MIT