Fork me on GitHub

Helpers

Methods to make views easier.


Helpers in caboose are blocks of code that can be imported easily into your controllers and views.

Via import

Helpers are located in the app/helpers directory and are modules named specifically. In order to be recognized by the import keyword, helper files must be named [helper-name]_helper.coffee or [helper-name]_helper.js. For instance, a string helper could be named string_helper.coffee and would be accessible by import 'StringHelper'. These helpers are just normal node modules.

app/helpers/string_helper.coffee

exports.ellipsis = (value, length) ->
  return value if value.length < length
  value.substr(0, length - 3) + '...'

exports.truncate = (value, length) ->
  value.substr(0, length)
    

You can use the imported helper within the controller, like in the for_example field below, or in the view by using the helper attribute.

app/controllers/posts_controller.coffee

import 'StringHelper'

class PostsController extends Controller
  helper StringHelper
  
  show: ->
    @post = {
      author: 'Mr. Clean'
      content: 'This is something really long and arbitrarily complex.  I&apos; not sure why someone would write something this long!'
      for_example: StringHelper.trucate('Truncate this to 10 characters', 10)
    }
    @render()
    

app/views/users/index.html.ejs

<%= @post.author %>

<%= ellipsis(@post.content, 80) %>

As an object

You can also use the helper attribute to make any object available to the view layer.

app/controllers/posts_controller.coffee

class PostsController extends Controller
  helper {
    random_quip: ->
      # generate some random quip
    moment: require('moment')
  }

  index: -> @render()
    

app/views/users/index.html.ejs

Welcome to my wonderful website!

It is currently <%= moment().format('LT') %>

<%= random_quip() %>