1
votes

I'm migrating a Backbone basic app to Marionette and I would like to use ICanHaz.js as a template system (based on Mustache).
I'm using AMD and Require.js and the only way to make ICanHaz.js working with it and Backbone was to use jvashishtha's version.

I first implemented the app in pure Backbone style.
In particular I used to load each template as raw strings with the Require.js' text plugin and then add the template to the ich object. This create a method in ich object that has the same name of the loaded template:

define([ 
'jquery',
'underscore',
'backbone',
'iCanHaz',
'models/Job',
'text!templates/Job.html'

], function( $, _, Backbone, ich, Job, jobTemplate) {     
    var JobView = Backbone.View.extend({
        render: function () {
             /* since the render function will be called iterativetly  
                at the second cycle the method ich.jobRowTpl has been already defined
                so ich will throw an error because I'm trying to overwrite it.
                That is the meaning of the following if (SEE: https://github.com/HenrikJoreteg/ICanHaz.js/issues/44#issuecomment-4036580)
             */
            if (_.isUndefined(ich.jobRowTpl)){ 
                ich.addTemplate('jobRowTpl', jobTemplate);
            };

            this.el = ich.jobRowTpl(this.model.toJSON());
            return this;
        }
    });
    return JobView;

});

So far so good. The problem comes with Marionette.
The previous code works fine in the Backbone version, but there is no need to define a render function in Marionette's views.
Marionette assumes the use of UnderscoreJS templates by default. Someone else has already asked how to use Mustache with Marionette.
From that answer I've tried to implement my solution. In app.js:

app.addInitializer(function(){

  //For using Marionette with ICH
  var templateName=''; //not sure if this would help, anyway it makes no difference
  Backbone.Marionette.Renderer.render = function(template, data){
    if (_.isUndefined(ich.template)){ 
          //this defines a new template in ich called templateName
          ich.addTemplate(templateName, template);
    };
    return ich.templateName(data);
  }

But the console throws me:

Uncaught TypeError: Object #<Object> has no method 'templateName' 

So the template has not been defined. Anyway, any hint if I'm in the right direction?

1
How do you apply the solution without using the text plugin? Just storing your templates in the index.html file?streetlight

1 Answers

3
votes

I think it's just a problem with your JS inside your renderer function.

This line:

return ich.templateName(data);

Will look for a template literally called "templateName"

What you want, since templateName is a variable is something like:

return ich[templateName](data);

Then it will interprete the value of the templateName variable instead.