Search code examples
knockout.jsjquery-templatesknockout-2.0

Can I use knockout as template engine?


I use knockout and jQuery.tmpl frameworks in my project and sometimes I use jquery-tmpl only to generate the HTML like this:

var html = $("#template").tmpl(data);
html.appendTo(destElement);  

I don't like that somewhere I have knockout templates for binding and somewhere jquery templates for html generation and also for binding.

I would like to know whether knockout provides ability to generate html from template like jquery tmpl does. If it does, I'll completely remove the jquery-tmpl, because in most cases I use it only for the html generation from templates.

Please advice


Solution

  • AFAIK Knockout does not support precompiling templates to be stored as a JavaScript variable like jQuery templates does.

    Hence, the example you've given in your question is not possible using only the Knockout template binding. The binding does provide some callbacks for post- and after-rendering, however this is not entirely the same as the input for those callbacks are compiled DOM elements rather than JavaScript references to it.

    On our current project we're using Handlebars as our templating engine, two main reasons why I'd choose this:

    1. jQuery templating is deprecated, no current official plugins exist and the jQuery UI team is unclear when/if they will include templating in the core.
    2. With Handlebars you can extract your templates to separate .handlebars files which can be precompiled from the command line.

    I don't use the knockout template binding, all my templates are extracted to separate files and are precompiled to separate .js files. All I have to do is to include the compiled .js files and I can access the templates as a JS variable.

    In case you'd choose jQuery templating and wanted to precompile your templates, you'd either have to add all templates to one HTML file and write some JavaScript that will take each template and convert it into JavaScript or you could write up a little node app that takes in your templates, converts them and outputs them again.