Search code examples
javascripttemplatesnestedknockout-templating

Javascript frameworks or knockoutjs library with nested Templating


Can I do nested templated with more than one hierarchy in for example kockoutjs library? http://knockoutjs.com/ or any other Javascript framework?

I have this View:

DataGrid:
Cell1, Cell2, Cell3, Within Cell4 is a ListBox.

Whatever it looks like in html. Is it possible with knockoutjs or any other javascript framework to create nested templates with multiple hierarchies?


Solution

  • Yes, it is possible in Knockout.

    You can specify a template name inside a root element:

    <ul data-bind="template: {name: listItemTmpl, foreach: items()}"></ul>
    

    and then inside that template you can also reference other templates via data-bind attribute:

    <script id="listItemTmpl" type="text/x-jquery-tmpl">
        <li>
            <h3 data-bind="text: name"></h3>
            <div data-bind="template: itemDetailsTmpl"></div>
        </li>
    </script>
    

    Knockout will apply root template binding and as it encounters data-bind attributes inside that template it applies those recursively.

    Im my sample it will apply listItemTmpl for each of items() and then for each of those it will use itemDetailsTmpl to show the details.

    Performance-wise it's very fast and unnoticable for the user.

    I use knockout templates in this manner in my current project and recursive templating lets me keep parts of my markup orginized in small sections.

    Is this something that you were looking for?