Rich
Rich

Reputation: 2096

Use of templates versus inside container element with Knockout.js

Quite a few examples I see of using knockout when showing a list of items makes use of a separate named template versus embedding the template inside the HTML element that encloses the entire list (div, ul, etc). Is this considered a best practice or a just a style thing? My question assumes there is no need for reuse of the template (in which case separating it out is obvious).

Upvotes: 1

Views: 552

Answers (1)

RP Niemeyer
RP Niemeyer

Reputation: 114792

The ability to use anonymous templates (children of the element) was just added in Knockout 2.0 with the inclusion of a native template engine. It was released in December 2011, so many examples that you encounter were likely created before it was available.

There are a few reasons why named templates are still valuable:

  • allows you to reuse templates (as you mentioned)
  • allows you to pull in a template externally (several ways to do it, but best is using: https://github.com/ifandelse/Knockout.js-External-Template-Engine).
  • the elements in a script tag will not be rendered prior to applying bindings, so you don't have to worry about hiding the elements initially and showing them after bindings are applied.
  • allow you to use other template engines (support for the deprecated jQuery Templates plugin is included), as anonymous templates only work out-of-the-box with the native template engine.

I think that it is helpful to use named templates for major sections of a page and then use the anonymous templates within the main template to keep it simple and clean.

So, really it is just personal preference at this point. Generally, I find it easier to read and write the anonymous templates.

Upvotes: 2

Related Questions