Ok so i added the type module and the error is gone but i still cant use Mustache, maybe i'm using it wrong i even tried to include it locally, so here you can see my code maybe you can help me with it, so without Mustache (working perfectly) :
The HTML side
<h2>Mustache Test</h2>
<p>Lorem, ipsum dolor sit amet consectetur adipisicing elit. Distinctio sint pariatur soluta nemo odit dolor ipsum laboriosam dolore ullam rerum commodi, vitae culpa totam autem praesentium, iste eveniet accusantium nam?</p>
<ul id="someData"></ul>
Javascript side :
$.ajax({
type: "GET",
url: "http://localhost:8000/api/displayAllUsers",
success: function (data) {
$.each(data, function (i, user) {
$("#someData").append('<li> name: ' user.name ' </li>');
});
},
error: function () {
console.log("Fail");
},
});
so this is working perfectly : results without Mustache
But i want to work with Mustache because i will need more complicated template in the future so here's what i tried:
Html Side:
<ul id="someData">
<template id ="user-template">
<li>
<p>
<strong>Name:</strong>
<span>{{name}}</span>
</p>
</li>
</template>
</ul>
Javascript side:
$(document).ready(function () {
var userTemplate = $("user-template").html();
function displayUsers(user){
$("#someData").append(Mustache.render(userTemplate, user));
}
$.ajax({
type: "GET",
url: "http://localhost:8000/api/displayAllUsers",
success: function (data) {
$.each(data, function (i, user) {
displayUsers(user);
});
},
error: function () {
console.log("Fail");
},
});
});
So i dont think I am wrong here, because in my browser console it saying that Mustache is not defined, here is the error:
and here you can see that nothing is displayed:
CodePudding user response:
The file you are trying to load contains an ECMAScript module.
To use it you need to rewrite your code so that it is also a module.
Essentially that means moving your code into a script element with type="module"
.
<script src="/js/mymodule.js" type="module"></script>
Then, inside your top level module you can load dependencies using the import
statement.
import mustache from "https://cdnjs.cloudflare.com/ajax/libs/mustache.js/4.2.0/mustache.min.js"
/* mustache is now a variable with the value imported from the module */
const view = {
title: "Joe",
calc: function () {
return 2 4;
}
};
const output = mustache.render("{{title}} spends {{calc}}", view);
console.log(output);
You can also inline it. Live demo under the fold.
<script type="module">
import mustache from "https://cdnjs.cloudflare.com/ajax/libs/mustache.js/4.2.0/mustache.min.js"
const view = {
title: "Joe",
calc: function () {
return 2 4;
}
};
const output = mustache.render("{{title}} spends {{calc}}", view);
console.log(output);
</script>