With the advice "mu is too short". And some crazy ideas, I came up with an interesting approach to complex patterns. * It almost works!
So, let's say I have this content (or data or view) that I want to put in a template:
var content = { title: "Black Book", girls: ["blonde", "brunette", "redhead"], digits: ['123', '456', '789'], calc: function () { return 2 + 4; } };
And I have a template like this:
<script type="text/template" id="template"> <h1>{{title}}</h1> <h3>{{calc}}</h3> <ul> <li><a href="{{digits}}">{{hair}}</a></li> </ul> </script>
And the end result I want is this:
<h1>Black Book</h1> <h3>6</h3> <ul> <li><a href="123">blonde</a></li> <li><a href="456">brunette</a></li> <li><a href="789">redhead</a></li> </ul>
The problem that we will face is that we have arrays (or lists) nested in the original content, and if we try to use Mustache.render (html, content), we get only one li element or the whole array in within the same href = "" attribute. So sad...
So, it fits, goes through the template several times. For the first time, go through and replace the top-level elements and configure the template for the next pass. The second time, configure one of the lists and configure the template for the third pass, etc. For how many layers of content you have. Here's the new starting template:
<script type="text/template" id="template"> <h1>{{title}}</h1> <h3>{{calc}}</h3> <ul> {{#hair}} {{#digits}} <li><a href="{{digits}}">{{hair}}</a></li> {{/digits}} {{/hair}} </ul> </script>
On the first pass, fill in the top-level filling and change {{digits}} to {{.}}
$.each(content, function (index, value) { template2 = template.replace(/{{title}}/ig, content.title) .replace(/{{calc}}/ig, content.calc) .replace(/{{digits}}/ig, '{{.}}'); });
Now you have this:
<h1>Black Book</h1> <h3>6</h3> <ul> {{#hair}} {{#digits}} <li><a href="{{.}}">{{hair}}</a></li> {{/digits}} {{/hair}} </ul>
In the next pass, we simply call Mustache.render (template2, content.digits); and this should give us:
<h1>Black Book</h1> <h3>6</h3> <ul> {{#hair}} <li><a href="123">{{hair}}</a></li> <li><a href="456">{{hair}}</a></li> <li><a href="789">{{hair}}</a></li> {{/hair}} </ul>
And that where my logic dies, haha. Any help thinking about this will swing! I think I could pull out the {{hair}} elements and just do $ .each through content.girls and stack.replace three times. Or I could try to start with the lowest level of content and go my own way. I dont know.
All this basically makes me wonder if there is any โlogically lessโ way for this type of nesting or multiple passages that need to be put in a mustache, does this make the steering wheels?