Skip to content

Rendering and Templating

conoremclaughlin edited this page Jan 22, 2013 · 1 revision

Inspired by Soundcloud's engineering

Rendering and templating is structured to make use of 'placeholder' elements to provide as much flexibility as possible. This provides a few benefits:

  • UI designers do not have to know how Bones or Backbone works to write templates.
  • Keeps messy design logic out of Backbone.View#render
  • Can render everything server-side for non-Javascript enabled clients - standard Bones
  • Can render everything client-side for maximum efficiency - standard Backbone
  • Or have the best of both worlds and partially render some content server-side. User then has something to look at while other content and widgets load dynamically

These placeholders are simply divs with certain data attributes depending on whether they're being sent from the server to client or just rendering.

  • Rendering: <div data-view="awesomeView" data-id="1">

  • Server to client: <div data-view="awesomeView" data-model="awesomeModel" data-id="__573AB57C">

The placeholders are generated by utils.partial(...), which places the data passed to partial in a store. This data is later retrieved for rendering the subview using the placeholder's data-id.

utils.renderSubviews can then be used to attach simpler Backbone views and models (initialized with only the id from data-id) to server-rendered content on the client (buttons that do not need the complete state of a model, for example). For more complex attaching, you can use the method shown in bones/examples/simple/App.server.bones.js

See individual function comments in shared/utils for more information on each method.

Notes

  • Templating should be used server-side and rendering client-side for ideal behavior.

Methods

  • utils.partial(view, options, store) template helper to create a view placeholder element.
  • utils.renderAll(view, options, store) recursively renders a view and its subviews.
  • utils.renderSubviews(element, store, shouldReplace) renders views for each placeholder within an element; attaches views if pre-existing content exists within placeholders.
  • utils.templateAll(title, options, store) recursively templates a view and its subviews.
  • utils.templateSubviews(html, store, selector, shouldReplace) templates views for each placeholder within a block of html; default leaves place

How To

How do I template my view and its subview?

Use templateAll with the name of your template and data you'd like to template.

servers/popularityApp#index(...)

...
models.Users.getNewestFriends(function(err, users) {
    if (err) return next(err);
    res.locals.main = Bones.utils.templateAll('Index', {
        users: users,
        model: models.User
    });
    return next();
});

How do I attach views client-side to server-side rendered content?

routers/yourDefaultRouter#initialize(...)

Bones.utils.renderSubviews('body');
Clone this wiki locally