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

3

9

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 JavaScript file.

Does anyone know how to do that?

I have the following code sample:

<!DOCTYPE html>
<html>
  <head>
    <title>Hogan.JS Test</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <script src="js/jquery-1.9.0.min.js"></script>
    <script src="js/hogan-2.0.0.min.js"></script>
    <script id="scriptTemplate" type="text/mustache">
      <p>Your text here: {{text}}</p>
    </script>
  </head>
  <body>
    <script>
      var data = {
        text: 'Hello World'
      };

      var template = $('#scriptTemplate').html();
      var compiledTemplate = Hogan.compile(template);
      var renderedTemplate = compiledTemplate.render(data);

      var box = document.createElement('div');
      box.innerHTML = renderedTemplate;
      document.body.insertBefore(box,document.body.childNodes[0]);
    </script>
  </body>
</html>

With the IDs I can address the templates but I always need a separate inline script. :-(

How does this work with external files?

Dungeon answered 30/1, 2013 at 10:20 Comment(0)
T
28

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>
Transpire answered 7/2, 2013 at 23:53 Comment(3)
Awesome! Thank you very much. That should be in the official Hogan.js documentation!Dungeon
Just a side note. What does the '!!!' mean in the compiled template? I can't seem to find an explanation of it anywhere.Arequipa
@JamesThomas ! means logical not. With a triple not, falsy values (0, false, "", null, undefined and NaN) becomes true and truthy values (true, Object, Function, Array, Number non-zero, String non-empty) turns into false. They are just checking if the variable templates exists... You can't add a property to a not defined objectGodrich
S
5

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.

Sphygmograph answered 18/8, 2013 at 19:51 Comment(0)
D
0

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 !

Dharana answered 6/6, 2014 at 20:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.