Loading a template from an external file in CanJS

437 Views Asked by At

If I add below code in my index.html then it's working fine but I want to define in external file and then I want to load it with can.view.

<script type="text/mustache" id="todosList">
     {{#todos}}
          <li>{{description}}</li>
     {{/todos}}
</script>

If I create separate html file how do I load a template from it?

2

There are 2 best solutions below

2
On
$('target-element').html(can.view('todosList', todolist-data))

This is the syntax to load external template in canJS.

2
On

can.view can directly load templates from a URL. From the can.view documentation:

Loading templates from a url

To load from a url, simply pass the location of the template to can.view. The location of the template needs an extension that matches the type of template:

document.getElementById('recipes')   
      .appendChild(can.view('templates/recipes.ejs', recipeData ) ) 

Note: If you are using RequireJS, the URL will be relative to its baseUrl.

In your case, if you named your file todos.mustache and it was in the templates directory, it would look like this:

document.getElementById('todos')   
      .appendChild(can.view('todos.mustache', recipeData ) )