Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Displaying conditional html with Knockout

I have an knockout observable array of activities which contains audits and comments. I've got the data from the server and sorted the array of activities based on the timestamp of the objects.

I'd like to be able to conditionally display html based on the type, so audits and comments will look different.

<!-- ko foreach: activities -->
<div class="audit" data-bind="visible: {activity is typeof Audit}"> 
    @*Do some audit html*@
</div>
<div class="comment" data-bind="visible: {activity is typeof Comment}"> 
    @*Do some comment html*@
</div>
<!-- /ko -->

I've got the following html but I don't know how do the condition, I just wrote something in above as a placeholder so you get the idea of what I'm trying to achieve.

I'm probably approaching this all wrong, any help much appreciated!

like image 479
Neil Avatar asked Jun 13 '12 15:06

Neil


1 Answers

Nayjest's solution should work if you change the visible binding to an if binding - that way it won't try render the parts with the title dependency.

A better solution, however, is probably to have two templates and execute them based on the type. You could have a method on the VM that takes $data and returns, for example, 'auditTemplate' or 'commentTemplate' depending on the result of something like $data instanceof Audit. You would then have two templates embedded as script tags with those ids:

<script id="auditTemplate" type="text/html">
<div class="audit">
<!-- Do some audit stuff -->
</div>
</script>

<script id="commentTemplate" type="text/html">
<div class="comment">
<!-- Do some comment stuff -->
</div>
</script>

And then in your VM, you'd have something like:

this.getTemplate = function(data) {
return (data instanceof Audit) ? 'auditTemplate' : 'commentTemplate'
}

In your page's html you'd do something like:

<!-- ko foreach: activities -->
<div databind="template: {name:$parent.getTemplate($data), data: $data}"></div>
<!-- /ko -->
like image 184
daedalus28 Avatar answered Sep 30 '22 17:09

daedalus28