Reputation: 3285
I have been looking for a simple basic example of using a Mustache template where the Mustache markup and templating stays in the HTML document (separation of concerns).
Here is where I am at:
<html>
<head>
<meta charset="utf-8">
<title></title>
<link rel="stylesheet" href="style.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/mustache.js/2.3.0/mustache.js"></script>
</head>
<body>
<div class="container">
<h2>Here is a person</h2>
<template id="theTemplate">
{{name}}
</template>
</div>
<script>
$(function() {
template = $('#theTemplate').html();
data = {
name: 'billy'
};
Mustache.render(template, data);
});
</script>
</body>
</html>
No errors are being thrown but it is not working!
Upvotes: 1
Views: 1119
Reputation: 337560
Mustache.render
returns a string which is the amalgamation of the template and the data from the provided object. It does not do anything else with that string, so if you want to update the DOM you will still need to do that manually. As you're using jQuery you can use append()
to do that:
$('h2').append(Mustache.render(template, data));
However, it would make more sense to include the whole h2
text value in the template to at least make its use worthwhile:
$(function() {
template = $('#theTemplate').html();
data = { name: 'billy' };
$('h2').text(Mustache.render(template, data));
});
<link rel="stylesheet" href="style.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/mustache.js/2.3.0/mustache.js"></script>
<div class="container">
<h2></h2>
<template id="theTemplate">
Here is a person named {{name}}
</template>
</div>
Upvotes: 2