Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
574 views
in Technique[技术] by (71.8m points)

load jQuery-Templates from external file?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...