user3105158
user3105158

Reputation: 61

Creating a template

Is there a way in knockoutjs to create a knockout template, but inject further HTML depending on values passed to it.

Example:

<script type="text/html" id="userMessageTemplate">
    <div class="chatContent">
        <span data-bind="text: userName"></span>
        <span data-bind="text: userMessageAlert "></span>
    </div>
</script>

This template currently has two span tags each bind to userName and userMessgeeAllert properties from the model respectfully.

Now I decide to use this template somewhere else but instead of userName I want it bind to orderNo, and also Add another span tag called Address:

<script type="text/html" id="userMessageTemplate">
    <div class="chatContent">
        <span data-bind="text: OrderNo"></span>
        <span data-bind="text: userMessageAlert "></span>
        <span data-bind="text: Address "></span>
    </div>
</script>

At the moment I would just create another template as above. But I would like to inject values, and based on those values create a template on the fly:

function (orderNo, userMessageAllert,Address)
{
// now based on the values create template 
}

Upvotes: 0

Views: 93

Answers (1)

Hans Roerdinkholder
Hans Roerdinkholder

Reputation: 3000

In this case, you could fix it by passing an array of properties to the template, and using a foreach-binding.

<script type="text/html" id="userMessageTemplate">
    <div class="chatContent" data-bind="foreach: $data">
        <span data-bind="text: $data"></span>
    </div>
</script>

In general, I would have a look at Knockout components. Not out yet, but will be soon, and it allows you to pass data into your template, to which it can respond intelligently.

Upvotes: 1

Related Questions