Last Updated: February 25, 2016
·
501
· sebastianconcpt

The world beyond the canvas, loading templates dynamically in Amber

Picture

This is the strategy I've used for loading templates in an Amber frontend:

  1. You start your Amber project as usual
  2. Make the controller (Widget) class that will use the html template
  3. Use either the initial static html file or
  4. The #renderOn: of some widget
  5. To make a div with an id where you'll insert the content: html div id: 'bigTemplate'
  6. Use require.js with the text plugin to load the template
  7. Use the callback of that call to make your controller continue the flow or react as appropriate

Some of the benefits I've perceived so far are:

  1. Copy paste a portion of code from the bootstrap examples or any other source
  2. Makes collaboration with designers that delivers html to be friction-less
  3. Allows you to use your favourite text editor for composing html
  4. Liberates you from using the canvas as the only way to get html rendered
  5. Profits from the caching features of the browser
  6. Makes your Amber source code smaller
  7. Improved separation of concerns by making your Amber source code more focused on behaviour (Controllers) and loosely coupled with looks (Views)

I bet that bootstrap's navbar will be a popular example:

AppNavBar>>renderOn: html 

  html div id: 'navbar'.

  "The navbar is a complex piece of html. 
  Lets forget the canvas way and grab it from a template. Bam!"
  require 
    value:(Array with: 'bower_components/text/text!views/navbar.html')
    value:[ :template | 
      '#navbar' asJQuery html: template].


AppNavBar>>initialize

  super initialize.

  AppRouter when: 'aboutToRoute' do:[ self clearActive ]

AppNavBar>>clearActive
  "Removes the .active class from all tabs"

  '.navbar-nav > li' asJQuery removeClass: 'active'