Share helper templates globally

silvenon edited this page Jul 22, 2012 · 9 revisions
Clone this wiki locally

Haml Coffee Assets allows you to mix in an object into each local template context by using HAML.globals. This allows you to look at your JST templates and make some helper templates available to each template. The following example adds all templates with a JST key name that starts with helpers/ to the globals:

HAML.globals = ->
  globals = {
    # Other global data or functions here

  for key, template of JST
    if helper = key.match /^helpers\/(.+)/
      globals[helper[1]] = template


Now you can create a template like helpers/link_to.hamlc with the following content:

%a{ href: "#{@link}" }= "#{@name}"

and reuse it in any template like this:

%h1 My header
!= @link_to name: 'Go to there...', link: '/' 

If your prefer a less verbose link_to method, you can make your globals acts as a facade to the helper templates by defining an API like:

HAML.globals = ->
    link_to: (name, link) -> JST['helper/link_to'](name: name, link: link)

Now you can use the link_to helper like

!= @link_to 'Go to there', '/'

This tip has been taken from the Haml Coffee Issue #25. Thanks Michał Taberski!