2

I'm currently using underscore.js for templating in a project, templates are stored in script tags with a type of text/template and loaded by id. I'm wondering if it's possible to continue to use the same system, but move the templates to a separate file?

The only way I can think about doing this is declaring the templates as global vars in a separate file, but that seems ugly.

Note: I don't want to use Jammit or some other build system for mashing everything together into a single file at deployment time, wondering if there's another solution.

Kim Sun-wu
  • 1,620
  • 1
  • 18
  • 26

1 Answers1

0

I personally use RequireJS to load my templates into a module but if you're looking for something else you can use Ajax.

As long as your templates are located on the same domain you can get them through an ajax request. I fail back to the following code if whomever using my widget isn't using an AMD compatible library:

$.ajax({
    url: root.WIDGET.BaseUrl + 'templates/widget.html',
    asynx: false, // synchonous call in case code tries to use template before it's loaded
    success: function (response) {
        widgetTemplate = response;
    }
});

This assumes you're using jQuery as well but the principle is the same if you're using something else.

JaredMcAteer
  • 21,688
  • 5
  • 49
  • 65