Search code examples
knockout.jsdurandal

Pass variable when binding template


Currently I bind a template this way

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

Now I need to pass a variable "host-company" = true while binding the template so that I can access that variable from comp-template view. How can I do this?

Note: currently I get company details from a json file and current view looks like this

 Host company: <span data-bind="if: text:host.company"></span>

This output to Host company: true. So I want something like this

<div data-bind="template: { name: 'comp-template', foreach: company, data: {host-company: text:host.company} }">

So that I can use the value of text:host.company in template as host-company.


Solution

  • First of all, you need to remove the -(dash) from the host-company because that makes it an invalid identifier. I would suggest to rename it to hostCompany or something like this.

    Assuming there is a property named - hostCompany which is a part of the objects inside of the company array, you can pass that variable inside of the data object wrapper like so -

    <div data-bind="template: { name: 'comp-template', foreach: company, data: { hostCompany: hostCompany } }">
    

    Or else like so -

    <div data-bind="template: { name: 'comp-template', foreach: company, data: { hostCompany: true } }">
    

    EDIT

    Assuming that you have an object host (on the root level) having a boolean property named company, the value of which you want to pass to the template, you can do so like below -

    <div data-bind="template: { name: 'comp-template', foreach: company, data: { hostCompany: host.company } }">
    

    You can access this parameter inside your template as -

    <!--ko if: hostCompany -->
        <span>Host company is true</span>
    <!--/ko-->