jquery - JS templating: How do if/else upon value? -


given json data/css.json such:

 { "css": [  { "group":"boxes", "css-class":"img",  "syntaxe": "img/css-metric.png",    "logic-english": "",    "level":"a1" },   { "group":"boxes", "css-class":"list", "syntaxe": "margin",    "logic-english": "",    "level":"a1" },  { "group":"boxes", "css-class":"list", "syntaxe": "margin-top",    "logic-english": "",    "level":"b2" },  { "group":"boxes", "css-class":"list", "syntaxe": "margin-right",  "logic-english": "",    "level":"b2" } ]} 

html such as:

<body id="anchor"></body> 

html's js such as:

<script src="http://cdnjs.cloudflare.com/ajax/libs/mustache.js/0.7.0/mustache.min.js"></script> <script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>  <script id="tpl" type="text/template">     {{#css}}<div class="{{css-class}}"><p class="{{level}} level">{{syntaxe}}</p><p class="logic-english">{{logic-english}}</p></div>{{/css}} </script>  <script>// code 4: works         $(function() {                 $.getjson('data/css.json', function(data) {                     var template = $('#tpl').html();                     var info = mustache.to_html(template, data);                     $('#anchor').html(info);                 });         }); </script> 

by editing #tpl (i guess), how create condition upon value such :

if css-class's value == "img" inject :

<img src="{{syntaxe}}" alt="an image" height="64" width="64"> 

else inject :

{{syntaxe}} 

?

as suggested per previous answer comments

another solution

using jquery's methods on elements after created.

you can make use of jquery's selector, .each(), , .replacewith() methods make fixes after templateing javascript has written new elements dom.

this like:

$(function() {     $.getjson('data/css.json', function(data) {         var template = $('#tpl').html();         var info = mustache.to_html(template, data);         $('#anchor').html(info);          $(".img").each(function(i) {             var myp = $(this).children("p").first(),                 myclass = myp.attr("class"),                 mysrc = myp.text();             myp.replacewith($("<img />", { class: myclass, height: 64, width: 64, src: mysrc }));         });     }); }); 

jquery references:

link mustache.js (i think he's using)


Comments

Popular posts from this blog

linux - Does gcc have any options to add version info in ELF binary file? -

android - send complex objects as post php java -

charts - What graph/dashboard product is facebook using in Dashboard: PUE & WUE -