Is it possible to load handlebar template with script tag? Or define handlebar templates programmatically in Ember.js

后端 未结 8 495
臣服心动
臣服心动 2021-01-31 10:38

Simply enough I do not want to define all my handlebar templates in my html file

I tried this



        
相关标签:
8条回答
  • 2021-01-31 11:01

    It is possible, and yes, you can do it without usage of another another another tool, just using ember.js and nothing else. i did it like this:

    1) html code. note that all handlebars files need to be loaded before using any of them. here, its just one file named handlebars.js

    <body>
      <script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
      <script>window.jQuery || document.write('<script src="js/libs/jquery-1.7.2.min.js"><\/script>')</script>
      <script src="js/libs/ember-0.9.8.1.min.js"></script>    
      <script src="js/handlebars.js"></script>
      <script src="js/app.js"></script>
    </body>  
    

    2) this file handlebars.js contains the following, using the compiler of ember

    var src = "Hello, <b>{{name}}</b>";
    Em.TEMPLATES["say-hello"] = Em.Handlebars.compile(src);
    

    3) and then inside your app.js file, just use it as it were available (which it is):

    var hu = Em.View.create({
        templateName: "say-hello",
        name: "Allô", 
        mouseDown: function() {  
        window.alert("hello world!");
    
      }
    });
    
    hu.appendTo("body");  
    
    0 讨论(0)
  • 2021-01-31 11:04

    Or define handlebar templates programatically in Ember.js

    You can define templates programmatically by using Ember.Handlebars.compile, see http://jsfiddle.net/pangratz666/wxrxT/:

    Ember.View.create({
        personName: 'Dr. Tobias Fünke',
        template: Ember.Handlebars.compile('Hello {{personName}}')
    }).append();​
    

    Or you add compiled templates to Ember.TEMPLATES array, see http://jsfiddle.net/pangratz666/58tFP/:

    Ember.TEMPLATES['myFunkyTemplate'] = Ember.Handlebars.compile('Hello {{personName}}');
    
    Ember.View.create({
        personName: 'Dr. Tobias Fünke',
        templateName: 'myFunkyTemplate'
    }).append();​
    

    I would recommend to use some tools like Richard Millan stated. Also take a look at interline/ember-skeleton which offers support for compilation of templates.

    0 讨论(0)
提交回复
热议问题