Search code examples
templatesknockout.jsjquery-templates

Is it possible preserve original layout, when using templates in knockoutjs with foreach?


I have an issue when rendering templated items within a ul with some pre-defined li elements, that i'd like the templating engine to respect:

This is what I'm trying to achieve:

<ul data-bind="{template: {name: itemTemplate, foreach: itemsToRender}}">
    <li class="first">some pre-info</li>
     //this is where I'd like knockout to render my templates
    <li class="last">som-post info</li>
</ul>

This is what I actually get:

<ul data-bind="{template: {name: itemTemplate, foreach: itemsToRender}}">
    //this is where all my templateItems get rendered
    <li class="first">some pre-info</li>
    <li class="last">som-post info</li>
</ul>

An obvious alternative is to use a template that rendered the entire ul, and looped over the child items, but this would render the entire template every time there was a change, and not just the updated items (li), which is the preferred way.


Solution

  • The best option is to use the containerless control-flow bindings available in KO 1.3 (in RC).

    It would look like:

    <ul>
      <li class="first">some pre-info</li>
      <!-- ko foreach: itemsToRender -->
        <li class="item" data-bind="text: name"></li> 
       <!-- /ko -->
      <li class="last">some post-info</li>
    </ul>
    

    or

    <ul>
      <li class="first">some pre-info</li>
      <!-- ko template: { name: 'itemTemplate', foreach: itemsToRender } -->
      <!-- /ko -->
      <li class="last">some post-info</li>
    </ul>
    
    <script id="itemTemplate" type="text/html">
        <li class="item" data-bind="text: name"></li> 
    </script>
    

    Sample: http://jsfiddle.net/rniemeyer/tzJU3/