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

左心房为你撑大大i 提交于 2019-12-22 08:46:31

问题


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>
    

    回答1:


    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.




    回答2:


    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>
    



    回答3:


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



    来源:https://stackoverflow.com/questions/7075424/icanhaz-js-possible-to-put-a-while-loop-in-template

  • 易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
    该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!