ICanHaz.js - Possible to put a while loop in template?
Asked Answered
B

3

4

Let's say I have a element, and inside it want to put an indefinite number of

  • items (based on the user's choices). Is there a way to create an ICanHaz template that allows for some sort of while loop. For instance:
        <ul>
         for(i = 0; i < numOfLi; i++)
           <li> {{ stuff }} </li>
        </ul>
    
  • Boulder answered 16/8, 2011 at 8:23 Comment(0)
    Q
    13

    icanhaz (moustache) does include a way to loop.

    In javascript:

    var listOfStuff = {stuff: [ 
                          {key: "1", desc: "First"},
                          {key: "2", desc: "Second"}
                      ]};
    $("#mySelectBox").append(ich.myTemplate(listOfStuff));
    

    In your view:

    <script id="myTemplate" type="text/html">
      {{#stuff}}
        <option value="{{key}}">{{desc}}</option>
      {{/stuff}}
    </script>
    
    <select id="mySelectBox">
    </select>
    

    The {{#stuff}} and {{/stuff}} delimit the list. Look at the Sections part of moustache for details.

    Edit: Make sure to check out this answer if you're using jQuery 1.9 or above.

    Quartus answered 16/12, 2011 at 18:24 Comment(3)
    I'm getting this error when trying out your solution: Uncaught Error: Syntax error, unrecognized expression: <option value="1">First</option> <option value="2">Second</option> It seems that it have parsed the mustache, but thy is this error raising?Kissiah
    Look out for jquery 1.9.1 with above construction. It won't work - take a look at problem/answer described in #15650987Kissiah
    Thanks @tkoomzaaskz. I've updated the answer to include your link.Quartus
    B
    0

    I'm not sure about iCanHaz, but John Resig (creator of JQuery) posted this method on his blog:

    See JavaScript Micro-Templating

    A sneak peak...

    <script type="text/html" id="user_tmpl">
      <% for ( var i = 0; i < users.length; i++ ) { %>
        <li><a href="<%=users[i].url%>"><%=users[i].name%></a></li>
      <% } %>
    </script>
    
    Burette answered 23/8, 2011 at 4:17 Comment(0)
    F
    -2

    Nope. Can't be done. You need to render the html dynamically.

    Floozy answered 16/8, 2011 at 19:40 Comment(1)
    well, this doesn't seem to be true thoughKissiah

    © 2022 - 2024 — McMap. All rights reserved.