2012-03-25 5 views
25

La mia app Emberjs è in esecuzione lentamente, quindi volevo precompilare il mio modello per semplificare un po 'il runtime. Comunque sono perso su come procedere. Ho letto http://handlebarsjs.com/precompilation.html e introduzione a Emberjs ma no, tutto quello che potevo fare era creare un file modello come indicato sul sito, e non riesco a capire cosa e come fare con questo file modello in Emberjs.Emberjs Handlebar precompilatore

Come posso precompilare i modelli in Emberjs? Cosa devo fare con il file modello per usarlo in Emberjs?

+0

Se si utilizza 'gulp' Recentemente ho pubblicato un pacchetto di NPM chiamato [brace-templates GULP-] (https://www.npmjs.org/package/gulp-ember -templates) che compilerà i tuoi template manubri in javascript e potrai quindi concatenarli in un unico file – Stuart

+0

possibili duplicati di [modo semplice per precompilare i modelli di Handlebar Emberjs con nodejs?] (http://stackoverflow.com/questions/9171583/ easy-way-to-precompile-emberjs-handlebar-templates-with-nodejs) – givanse

risposta

-16

È possibile impostare l'output di manubri precompilati sulla proprietà del modello (non su templateName) nella vista ember. Questo è ciò che fa brace anche sotto il cofano

MyApp.MyView = Ember.View.extend({ 
    templateName: "myViewWhatever", 
    template: Ember.Handlebars.compile('<p>{{blah}}</p>'), 
}) 
+9

Questa non è una precompilazione. – hekevintran

+5

questo compila ancora sul client –

3

Ecco una sostanza che mostra come precompilare manubrio modelli e aggiungere il risultato all'oggetto Ember.TEMPLATES, che Ember consulta per risolvere modelli definiti.

https://gist.github.com/2013669

+1

Come posso precompilare i partial? – Manoharan

37

per chiarire, ad esempio Thomas' come scritto sta ancora facendo la compilazione del modello in fase di esecuzione. Credo che il suo punto, però, era che, dopo aver caricato il precompiled Ember-Handlebars templates si può fare questo:

MyApp.MyView = Ember.View.extend({ 
    template: Ember.TEMPLATES.mytemplate, 
}) 

Il problema con l'utilizzo Handlebars' built-in precompiler è che l'attuazione Manubrio di Ember aggiunge alcune funzionalità in cima a ciò fornisce manubrio stesso, in modo ti consigliamo di installare ember-precompile package, che fornisce fondamentalmente la stessa interfaccia dell'utilità da riga di comando handlebars, ma utilizzando l'implementazione di Handlebars di Ember.

Questo eviterà di dover modificare tutti i tuoi templateName s in template s e di dover aggiungere lo Ember.TEMPLATES... in ogni vista, poiché aggiorna automaticamente la cache dei modelli incorporata di Ember.

Quindi, supponendo che hai già caricato il file di pre-rispettato templates.js come uscita dal ember-precompile templates/*.handlebars -f templates/templates.js, ecco un frammento di esempio più completo di un ordine di importazione/inizializzazione dei lavoratori:

<script src="/lib/handlebars-1.0.0.beta.6.js"></script> 
<script src="/lib/ember-1.0.pre.js"></script> 
<script src="/lib/ember-data-latest.js"></script> 
<script> 
    var App = Ember.Application.create(); 
</script> 
<script src="/templates/templates.js"></script> 
<script src="/js/models.js"></script> 
<script src="/js/views.js"></script> 
<script src="/js/controllers.js"></script> 
<script src="/js/router.js"></script> 
<script> 
    App.initialize(); 
</script> 
+1

Penso che i tuoi esempi mostrino la compilazione di manubri di vanilla. Avevo l'impressione che Ember.Handlebars dovesse essere usato per precompilare i template. –

+1

@LukeMelia hai perfettamente ragione, non è stato molto chiaro - ho chiamato lo script "manubrio" di Ember-Precompile sulla mia macchina, che è davvero confuso. Ora è 'ember-precompile' e installabile tramite NPM :) –

+0

Ho scoperto che i miei modelli compilati utilizzavano" Handlebars.helpers "invece di" Ember.Handlebar.helpers ". E così, la maggior parte dei comuni aiutanti di brace - vista, parziale, uscita, ecc. Non erano disponibili, e mi stava facendo impazzire. Grazie! – Shiprack

0

È possibile precompilare nel client di browser, come ha affermato Thomas Bartelmess.

Si può anche precompilare usando manubrio tramite nodejs (presi dalla mia molto personale Jakefile):

var Handlebars = require('handlebars'); 
precompile = (function() { 
    //Lovingly extracted from Ember's sources. 
    var objectCreate = Object.create || function (parent) { 
      function F() {} 
      F.prototype = parent; 
      return new F(); 
     }, 
     Compiler = function() {}, 
     JavaScriptCompiler = function() {}; 

    Compiler.prototype = objectCreate(Handlebars.Compiler.prototype); 
    Compiler.prototype.compiler = Compiler; 
    JavaScriptCompiler.prototype = objectCreate(Handlebars.JavaScriptCompiler.prototype); 
    JavaScriptCompiler.prototype.compiler = JavaScriptCompiler; 
    JavaScriptCompiler.prototype.namespace = "Ember.Handlebars"; 
    JavaScriptCompiler.prototype.initializeBuffer = function() { 
     return "''"; 
    }; 
    JavaScriptCompiler.prototype.appendToBuffer = function (string) { 
     return "data.buffer.push(" + string + ");"; 
    }; 
    Compiler.prototype.mustache = function (mustache) { 
     if (mustache.params.length || mustache.hash) { 
      return Handlebars.Compiler.prototype.mustache.call(this, mustache); 
     } else { 
      var id = new Handlebars.AST.IdNode(['_triageMustache']); 
      if (!mustache.escaped) { 
       mustache.hash = mustache.hash || new Handlebars.AST.HashNode([]); 
       mustache.hash.pairs.push(["unescaped", new Handlebars.AST.StringNode("true")]); 
      } 
      mustache = new Handlebars.AST.MustacheNode([id].concat([mustache.id]), mustache.hash, !mustache.escaped); 
      return Handlebars.Compiler.prototype.mustache.call(this, mustache); 
     } 
    }; 
    return function precompile(string) { 
     var ast = Handlebars.parse(string); 
     var options = { 
      knownHelpers : { 
       action : true, 
       unbound : true, 
       bindAttr : true, 
       template : true, 
       view : true, 
       _triageMustache : true 
      }, 
      data : true, 
      stringParams : true 
     }; 

     var environment = new Compiler().compile(ast, options); 
     return new JavaScriptCompiler().compile(environment, options, undefined, true); 
    }; 
}()); 

strPrecompiledTemplate = item.handlebarsTemplateFolders.map(function (dir) { 
    console.info("\tProcessing " + dir); 
    return readdirRecursiveSync(dir).map(function (file) { 
     console.info("\t\t" + file); 
     var content = fs.readFileSync(file, 'utf-8'); 
     content = Handlebars.precompile(content); 
     file = file.replace(/\.[^\.]+$/, '').replace(/^src\//g, '').substr(dir.length).replace(/^\/+/, ''); 
     // Pay attention: The wrap in Ember.Handlebars.template() is important! 
     return "Ember.TEMPLATES['"+file+"'] = Ember.Handlebars.template("+content+");"; 
    }).join("\r\n"); 
}).join("\r\n"); 
0

sto usando Gulp per build, e precompilazione modelli si presenta così:

var handlebars = require('gulp-ember-handlebars'); 
var concat = require('gulp-concat'); 

var SRC = { 
    TEMPLATES: ['app/templates/**/*.{hbs,html}'] 
}; 

gulp.task('templates', function() { 
    return gulp.src(SRC.TEMPLATES) 
    .pipe(handlebars({outputType: 'browser'})) 
    .pipe(concat('templates.js')) 
    .pipe(gulp.dest(DEST.SCRIPTS)); 
}); 

allora io uso la libreria di runtime manubrio piuttosto che la versione completa.

Ember-Manubrio: https://www.npmjs.org/package/gulp-ember-handlebars