How can Set external template URL in knockout js

Viewed 68

I am wondering how can I separate the knockout template file and use it in my projects. My projects worked correctly, but when I put my template in an external file, it goes wrong.

One thing that I don't know, what the template extension should be?

I made two templates as person-template.js and person-template.js with the same below code:

<script type="text/html" id="person-template">
    <h3 data-bind="text: name"></h3>
    <p>Credits: <span data-bind="text: credits"></span></p>
</script>

and my page:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script type='text/javascript' src='knockout-3.5.1.js'></script>
    <title>Document</title>
</head>
<body>

    <h2>Participants</h2>
    Here are the participants:
    <div data-bind="template: { name: 'person-template', templateUrl: '.',  foreach: people }"></div>
     


    <script type="text/javascript">
     function MyViewModel() {
         this.people = [
             { name: 'Franklin', credits: 250 },
             { name: 'Mario', credits: 5800 }
         ]
     }
     ko.applyBindings(new MyViewModel());
    
</script>
</body>
</html>

And I got this error

Uncaught Error: Unable to process binding "template: function(){return { name:'person-template',templateUrl:'.',foreach:people} }" Message: Cannot find template with ID person-template at a.ba.a.ca.makeTemplateSource (knockout-3.5.1.js:118)

0 Answers
Related