Вопрос

I've been using plunker for about a month now. I was making a backbonejs plunker and I see that Underscore loses my template settings and falls back to ERB style templating whereas I would like the Mustache style syntax {{ myData }} . I am setting the value in my app.js (which I always do in my apps) but for some reason, it keeps changing back to ERB <%=boo%>. Can someone help me get my template setting straightened out? plunker using underscore templating you'll need to view the console output in chrome dev tools or firebug or equiv...

Thanks for any tips or tricks. I tried

_.templateSettings = { 
   interpolate: /\{\{(.+?)\}\}/g,
   evaluate: /\[\[(.+?)\]\]/g
 }; 

when I console.log(_.templateSettings) in my app.js file right after setting, everything seems correct, but my templates aren't being processed. I can break inside a view and run the same console.log() and I see it has been switched back to ERB style. Does anyone know how to make my settings stick? Perhaps it's a plunker issue because I have used this method many times without a problem.

which usually does the trick. I even try... window._ = _;

Thanks for any help, tips, tricks, etc...

Это было полезно?

Решение

You just have an order of execution problem. Your app.js says this:

var app = {
  init: function () {
    _.templateSettings = {
      interpolate: /\{\{(.+?)\}\}/g,
      evaluate: /\[\[(.+?)\]\]/g
    };
    window._ = _;
  },
  //...

so your template settings won't be applied until someone calls app.init(). If we have a look at one of your views in main.js, we'll see things like this:

Zurg.Views.AltContent = app.View.extend({
  #...
  template: _.template([...].join('')),
  #...

So your _.template call happens while main.js is being loaded and parsed but app.init() isn't called until later.

All you need to do is arrange for things to happen in this order:

  1. Load the libaries (jQuery, Underscore, Backbone, ...)
  2. Adjust the _.templateSettings to use your delimiters.
  3. Load your views.

If you move the _.templateSettings to outside app.init:

_.templateSettings = {
    interpolate: /\{\{(.+?)\}\}/g,
    evaluate: /\[\[(.+?)\]\]/g
};

var app = {
  init: function () {
    // Whatever you really need to initialize things goes here...
  },
  //...

then everything should work out. BTW, your window._ = _; trick wasn't doing anything useful so I took it out. And you should include an escape regex in _.templateSettings too, you might not need it but completeness is good.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top