load jQuery-Templates from external file?
Asked Answered
S

3

24

I just started using jQuery's template engine. Which looks quite nice so far. Yet i wonder if it's possible to load templates from an external file somehow. Imagine having loads of templates. This would mess up the html-code and is also not cacheable and has to be downloaded on every request.

I was hoping there is a way to define them all in an external file and then load them and store the compiled templates into localStorage.

Does anyone have an idea how to load them from an external file?

Sacci answered 6/12, 2010 at 11:57 Comment(0)
B
15

you can load this template with ajax.

<script>
  var movies = [
    { Name: "The Red Violin", ReleaseYear: "1998", Director: "François Girard" },
    { Name: "Eyes Wide Shut", ReleaseYear: "1999", Director: "Stanley Kubrick" },
    { Name: "The Inheritance", ReleaseYear: "1976", Director: "Mauro Bolognini" }
  ];

  $.get("templates/movieTemplate.html", function(data, textStatus, XMLHttpRequest){
    var markup = data; //"<tr><td colspan='2'>${Name}</td><td>Released: ${ReleaseYear}</td><td>Director: ${Director}</td></tr>"

    /* Compile markup string as a named template */
    $.template( "movieTemplate", markup );

    /* Render the named template */
    $.tmpl( "movieTemplate", movies ).appendTo( "#movieList" );
  });
</script>

You can add now the localstorage logic or an array for the loaded templates if you want to load any template only once.

Bolus answered 6/12, 2010 at 12:15 Comment(2)
+1 for including example on using .template() to compile and $.tmpl() to render. This allows repeat calls to $.tmpl() later, without a need to fetch or compile.Allergen
It gives: TypeError: $.template is not a functionAlleris
P
1

I wrote litle lib as jQuery plugin for ajax rendering html on appear block with indexDB caching in browser jQuery HTML Template Loader

Parquetry answered 13/4, 2015 at 7:46 Comment(0)
S
0

I recently wrote a javascript library to assist with this:

https://www.github.com/stevenmhunt/tmpl.loader

You can add jsRender or any other kind of template files using the <link> tag and they automatically register.

Stonedeaf answered 13/9, 2012 at 14:27 Comment(2)
Link is broken. :(Bigner
Sorry about that, I changed my github name years ago. The link is fixed now.Stonedeaf

© 2022 - 2024 — McMap. All rights reserved.