November 22nd, 2011

How to use Knockout.js with XSLT

Posted in Code |

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:

  1. Convert the attribute:

    data-bind="..."

    into an

    <xsl:attribute name="data-bind">

    Like this:

    <li>
     <xsl:attribute name="data-bind">
      css: {'active': visible()}
     </xsl:attribute>
    </li>
  2. Do a search and replace exchanging the curly braces with XML-safe entities:
    	"{" to "&#123;"
    	"}" to "&#125"

    So the final XSLT should look like this:

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

     

Ugly, I know! But now it will work.

flattr this!

4 Responses to “How to use Knockout.js with XSLT”

  1. Stephan says:

    My suggestions is not to do the xslt in the first place :)

  2. Jakob says:

    That notion is the key learning hidden between the lines of this post! (-:

  3. Mike says:

    Thanks for helping me out of my bind *cough* and its xslt so ugly is fine.

  4. Jakob says:

    Hey Mike,
    Glad to help! :)
    And yeah, there’s not much room for aesthetics in the XSLT department. I really hope it goes away soon!

Leave a Reply