Scott Weinstein
Scott Weinstein

Reputation: 19117

Can knockout.js use templates to generate templates?

I'm trying to use knockout to templates to generate templates.

Along the lines of

Html:

<script id="searchField-template" type="text/html">
    <li data-bind="text: name"></li>
</script>

<script id="template-template"  type="text/html">
    <ul data-bind="template: { name: 'searchField-template', foreach: ${name} }" ></ul>
</script>    

JS:

var viewModel = {
    Title: [{
        name: "Title1"},
    {
        name: "Title2"},
    {
        name: "Title3"}],
    Manager: [{
        name: "Manager1"},
    {
        name: "Manager2"},
    {
        name: "Manager3"}],

    Defn: [{
        name: "Title"},
    {
        name: "Manager"}]

};

ko.applyBindings(viewModel);

runnable sample here: http://jsfiddle.net/scottwww/yQZUE/2/

It seems that the problem is with how curly braces are interpreted.

Any suggestions?

Upvotes: 2

Views: 1507

Answers (3)

neeebzz
neeebzz

Reputation: 11538

Here you go >

http://jsfiddle.net/vwP3w/2/

Upvotes: 2

Scott Weinstein
Scott Weinstein

Reputation: 19117

Not sure this is the right way, but a reference to the vm helps.

http://jsfiddle.net/scottwww/vwP3w/1/

HTML:

<div data-bind="template: { name: 'template-template', foreach: Defn }"></div>

<script id="searchField-template" type="text/html">
    <li data-bind="text: name"></li>
</script>

<script id="template-template"  type="text/html">
    <ul data-bind="template: { name: 'searchField-template', foreach: vm[$data.name] }" ></ul>
</script>    

JS:

var viewModel = {
    Title: [{
        name: "Title1"},
    {
        name: "Title2"},
    {
        name: "Title3"}],
    Manager: [{
        name: "Manager1"},
    {
        name: "Manager2"},
    {
        name: "Manager3"}],

    Defn: [{
        name: "Title"},
    {
        name: "Manager"}]

};
window.vm = viewModel;
ko.applyBindings(viewModel);

Upvotes: 2

David Wick
David Wick

Reputation: 7095

use the $data variable inside the nested template.

http://jsfiddle.net/dwick/yQZUE/3/

Upvotes: 0

Related Questions