title: Handlebars, loading external template files
body: <p>My goal is to put all my Handlebars templates in a single folder, as so:</p>
  
  <pre><code>templates/products.hbs
  templates/comments.hbs
  </code></pre>
  
  <p>I found this snippet in a few places via a cursory Google search, which apparently will load in Handlebar templates in external files, which makes much more sense than putting a bunch of templates in a single index file.</p>
  
  <pre><code>(function getTemplateAjax(path) {
      var source;
      var template;
  
      $.ajax({
          url: path, //ex. js/templates/mytemplate.handlebars
          cache: true,
          success: function(data) {
              source    = data;
              template  = Handlebars.compile(source);
              $('#target').html(template);
          }               
      });         
  })()
  </code></pre>
  
  <p>The problem is, I don't understand this function or how to use it. Why is the whole function wrapped in parentheses and then made a function call? e.g. <code>(function x() { ... })()</code> I don't know what this is doing.</p>
  
  <p>And if I'm not mistaken, looks like <code>$('#target')</code> is hardcoded when it shouldn't be. Furthermore, isn't this supposed to set a <code>data</code> variable somewhere so the variables referenced in the template will work?? Seems the correct function should be:</p>
  
  <pre><code>function getTemplateAjax(path, target, jsonData) {
    var source;
    var template;
  
    $.ajax({
      url: path, //ex. js/templates/mytemplate.handlebars
      cache: true,
      success: function(data) {
        source    = data;
        template  = Handlebars.compile(source);
        $(target).html(template(jsonData));
      }               
    });         
  }
  </code></pre>
  
  <p>Side note: if someone could point me to a better template engine, one that actually natively supports external template files, and is better organized than Handlebars, I'd be eternally grateful.</p>
  
  <p>Another issue: I can't actually name my files <code>mytemplate.hbs</code>, because when the Ajax call happens, it sees it as a binary file and it comes through as binary. I suppose this is an issue of setting the server's mime type for .hbs to text/html or text/plain, but the issue is that this is a Grunt server and I'm not sure how to change its mime types.</p>