Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I dynamically render HTML using Meteor Spacebars templates?

So let's say I'm storing <div>{{name}}</div> and <div>{{age}}</div> in my database. Then I want to take the first HTML string and render it in a template - {{> template1}} which just renders the first string with the {{name}} handlebar in it. Then I want to give that newly generated template/html data, so that it can fill in the handlebar with the actual name from the database, so that we would get <div>John</div>. I've tried doing

<template name="firstTemplate">
    {{#with dataGetter}}
        {{> template1}}
    {{/with}}
</template>

Where template1 is defined as

<template name="template1">
    {{{templateInfo}}}
</template>

And templateInfo is the helper that returns the aforementioned html string with the handlebar in it from the database.

dataGetter is just this (just an example, I'm working with differently named collections)

Template.firstTemplate.dataGetter = function() {
    return Users.findOne({_id: Session.get("userID")});
}

I can't get the {{name}} to populate. I've tried it a couple of different ways, but it seems like Meteor doesn't understand that the handlebars in the string need to be evaluated with the data. I'm on 0.7.0 so no Blaze, I can't upgrade at the moment due to the other packages I'm using, they just don't have 0.8+ version support as of yet. Any ideas on how I can get this to work are much appreciated.

like image 404
Danail Gabenski Avatar asked May 01 '14 19:05

Danail Gabenski


1 Answers

In 1.0 none of the methods described above work. I got this to work with the function below defined in the client code. The key was to pass the options { isTemplate: true} to the compile function.

var compileTemplate = function(name, html_text) {
  try {
    var compiled = SpacebarsCompiler.compile(html_text, { isTemplate:true });
      var renderer = eval(compiled);
      console.log('redered:',renderer);
      //Template[name] = new Template(name,renderer);
      UI.Template.__define__(name, renderer);
  } catch (err){
    console.log('Error compiling template:' + html_text);
    console.log(err.message);
  }
};

The you can call with something like this on the client:

compileTemplate('faceplate', '<span>Hello!!!!!!{{_id}}</span>');

This will render with a UI dynamic in your html

{{> Template.dynamic template='faceplate'}}

like image 117
user3354036 Avatar answered Sep 20 '22 00:09

user3354036