mustache.js – templating from other html file

mustache.js is Logic-less {{mustache}} templates with JavaScript

in my work, MVC structure, we get the data with json format, and the json format must convert to view / html structure, and user get the view from that.

benefit from json, you can make anything format, anything (text) value, it so freely. the freely of format need more freely (template) view but still need easy to maintain and modify with less logic😀

<!doctype html>
<html lang="en">
  <head>
    <title>Mustache.js External Method</title>
    <script type="text/javascript" src="jquery.min.js" ></script>
    <script type="text/javascript" src="mustache.js" ></script>
    <script>
      $(document).ready(function(){
        var view = {
          name : "Gw",
          occupation : "Web Developer"
        };
 
        $("#templates").load("template.html",function(){
    
          var template1 = document.getElementById('template1').innerHTML;
          var template2 = document.getElementById('template2').innerHTML;
          var template3 = document.getElementById('template3').innerHTML;
          
          var output1 = Mustache.render(template1, view);
          var output2 = Mustache.render(template2, view);
          var output3 = Mustache.render(template3, view);
          
          $("#div1").html(output1);
          $("#div2").html(output2);
          $("#div3").html(output3);
        });
      });
    </script>
  </head>
  <body>
    <div id="div1"></div>
    <div id="div2"></div>
    <div id="div3"></div>
    
    <div id="templates" style="display: none;"></div>
  </body>
</html>

and the template.html


<div id="template1">
<h1 style='color:hotpink;'>{{name}}</h1>
</div>

<div id="template2">
<div style='color:blue;'>{{name}}</div>
</div>

<div id="template3">
<p style='color:red;'><span>{{name}} occupation is {{occupation}}</span></p>
</div>

mustache

Published by

G3n1k

just to remember what i had known :)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s