Using Visualforce and Knockout.js without a container element

I have been working on a new Salesforce project experimenting with Knockout.js and Visualforce. Knockout provides a great way of iterating over data directly from the HTML elements. The problem, which Bob Buzzard points out in his blog post, is that Visualforce removes all HTML comments. Check out his post for a more in-depth look at the problem.

Now Bob found a workaround to this by escaping out characters of the HTML comment and rendering them with a Visualforce outputText component.

!-- ko foreach: daysOfWeek --

Unfortunately this looks really ugly when you start nesting multiple statements together, forcing my eyes to glaze over as I stare into the spiraling abyss that is my code.

In an effort to make the syntax more elegant I decided to wrap Bob's workaround into an Visualforce Component. As of API version 25, we can create Visualforce components without any additional HTML markup added by simply setting the "layout" attribute to "none". You can find the below code as a Github Gist here.


            !-- ko {!statement} --
            !-- /ko --


Knockout Opening Tag:


Knockout Opening Tag with Closing Tag:


This automatically adds the Knockout closing tag to the end. Useful for rendering text without a container.

Knockout Closing Tag

Renders just the knockout closing tag by itself.

As you can see this allows you to markup your Visualforce pages in a much more elegant way. I hope this post was useful, and a special thanks to Bob Buzzard for coming up with this workaround. Be sure to vote up his idea to stop stripping HTML comments from Visualforce pages.

Vote on HN

comments powered by Disqus