How to load templates with Hogan.JS from an external file?

后端 未结 3 886
暖寄归人
暖寄归人 2020-12-23 15:36

I use Hogan.JS as JavaScript templating library. It is supposed to load JavaScript templates from external files. One can probably outsource several templates in an external

相关标签:
3条回答
  • 2020-12-23 16:05

    I had the same question and ended up with a different way of doing things than Phuong's, I thought I'd share it.

    Server side, I compile the template and save it to a file with the following script :

    // template will be a string
    var template = hogan.compile(
        '<span>{{text}}</span>',
        { asString: true }
    );
    
    // prepare the content of the file we are about to create
    var content =
        'if(!templates) var templates = {};' +
        'templates.example = ' + template + ';';
    
    // write to a file that will be called by the client
    fs.writeFile('compiledTemplate.js', content, function(err){
        if(err){ console.log('Oops !') }
    });
    

    And client side, I do :

    <!DOCTYPE html>
    <html>
      <head>
        <script src="js/hogan-2.0.0.js"></script>
        <script src="js/compiledTemplate.js"></script>
      </head>
      <body>
        <script>
    
          var data = {
            text: 'Hello World'
          };
    
          var template = new Hogan.Template(templates.example),
              html = template.render(data);
    
          var box = document.createElement('div');
          box.innerHTML = html;
          document.body.insertBefore(box,document.body.childNodes[0]);
    
        </script>
      </body>
    </html>
    

    I hope it helps !

    0 讨论(0)
  • 2020-12-23 16:17

    You have two options to load external templates:

    1. Pre-compiling the templates (the best feature of Hogan.js IMHO) or
    2. Using require.js's text plugin to load the template string

    Unfortunately, the documentation for pre-compiling Hogan.js templates is non-existent. If you have a copy of the Github repo then inside the bin directory is a script called hulk that will do the job. It requires nodejs along with some npm modules (i.e. nopt and mkdirp) installed.

    Once you have nodejs and those modules installed, given a template file Test.hogan:

    <p>Your text here: {{text}}</p>
    

    You can pre-compile the script using the following command:

    hulk Test.hogan
    

    Resulting in the following text:

    if (!!!templates) var templates = {};
    templates["Test"] = new Hogan.Template({code: function (c,p,i) { var t=this;t.b(i=i||"");t.b("<p>Your text here: ");t.b(t.v(t.f("text",c,p,0)));t.b("</p>");return t.fl(); },partials: {}, subs: {  }});
    

    Save this to a file called templates.js

    Now in your HTML page, you would load that templates.js file and it creates a global object called templates where the compiled template function is in key "Test". You can also leave out the hogan.js file since that is the compiler (and your templates are now pre-compiled) and just include the template.js file that comes in the distribution.

    <!DOCTYPE html>
    <html>
      <head>
        <title>Hogan.JS Test</title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <script src="js/template.js"></script>
        <script src="js/templates.js"></script>
      </head>
      <body>
        <script>
          var data = {
            text: 'Hello World'
          };
    
          var compiledTemplate = templates['Test'];
          var renderedTemplate = compiledTemplate.render(data);
    
          var box = document.createElement('div');
          box.innerHTML = renderedTemplate;
          document.body.insertBefore(box,document.body.childNodes[0]);
        </script>
      </body>
    </html>
    

    Note: I did have some problems using the current master branch of the Github repo since it generated a template that uses a different constructor than the one used in the 2.0.0 template version. If you use hulk be sure to use the template.js file located in the lib folder.

    Alternatively, you can use require.js and the text plugin. Download them and save them to your js folder. Then you'll need to add a require statement to load the template text:

    <!DOCTYPE html>
    <html>
      <head>
        <script src="js/hogan-2.0.0.js"></script>
        <script src="js/require.js"></script>
      </head>
      <body>
        <script>
          var data = {
            text: 'Hello World'
          };
    
          require(['js/text!Test.hogan'], function(testHoganText) {
            // testHoganText contains the text of your template
            var compiled = Hogan.compile(testHoganText);
            var renderedTemplate = compiled.render(data);
    
            var box = document.createElement('div');
            box.innerHTML = renderedTemplate;
            document.body.insertBefore(box,document.body.childNodes[0]);
          });
        </script>
      </body>
    </html>
    
    0 讨论(0)
  • 2020-12-23 16:23

    There is another way that works very well if you are not using node nor if you want to rely require.js

    You can simply use the jQuery $.get to get the path to the template file. So an example looks like this:

    $.get('templates/book.hogan', function(templates){
                var extTemplate = $(templates).filter('#book-tpl').html();
                var template = Hogan.compile(extTemplate);
                var rendered = template.render(datum);
                $('.marketing').append(rendered);
    });
    

    The template can simply be a .html file (I just use .hogan) and all of the html in the template should be wrapped in a script tag with a unique id so you can get the id here. Datum comes from on('typeahead:selected') but that's irrelevant I just thought I should explain since it is in the code with no other reference.

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