How to use Knockout.js with XSLT

Written by Jakob Løkke Madsen

22. November 2011

As you may know, Knockout.js uses inline Javascript for it’s elegant, declarative bindings:

<li data-bind="css: {'active': visible()}"></li>

But if you use XSLT to render your HTML, it may fail because the curly-braces may not be supported in attributes.

To make this work, you need to do two things:

Convert the attribute: data-bind into an <xsl:attribute name="data-bind">

Like so:

<li>
    <xsl:attribute name="data-bind">
        css: {'active': visible()}
    </xsl:attribute>
</li>

Do a search and replace exchanging the curly braces with XML-safe entities:

"{" to "&amp;#123;"
"}" to "&amp;#125"

So the final XSLT should look like this:

<li>
    <xsl:attribute name="data-bind">
        css: &amp;#125'active': visible()&amp;#125
    </xsl:attribute>
</li>

Ugly, I know! But now it will work.

Edit: As Christian and Sam pointed out to me, you can also just escape the entities by using double curlies: attr{{id: prop}}. Thanks for pointing that out, guys! :)

comments powered byDisqus