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

16,434

Solution 1

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>

Solution 2

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.

Share:
16,434
Benny Neugebauer
Author by

Benny Neugebauer

Hi there 👋 🙂 My name is Benny (he/him). ☀️️ I code for South Pole during the day. 🌑 I record for TypeScript TV during the night. 💦 And if there is some time left, I go wakeboarding.

Updated on July 17, 2022

Comments

  • Benny Neugebauer
    Benny Neugebauer almost 2 years

    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?

  • Benny Neugebauer
    Benny Neugebauer over 11 years
    Awesome! Thank you very much. That should be in the official Hogan.js documentation!
  • James Thomas
    James Thomas almost 10 years
    Just a side note. What does the '!!!' mean in the compiled template? I can't seem to find an explanation of it anywhere.
  • BernaMariano
    BernaMariano over 9 years
    @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 object