Best practice for adding render helpers that can be accessed in templates?

147 views
Skip to first unread message

Charles Davison

unread,
Oct 28, 2013, 7:57:59 AM10/28/13
to chapl...@googlegroups.com
I'm using the standard underscore templating library.  What's the 'Chaplin' way of adding render helpers that can be access from within a template? E.g. formatDate(), etc.?

Thanks
Charlie

Paul Miller

unread,
Oct 28, 2013, 11:15:56 AM10/28/13
to chapl...@googlegroups.com
There is no chaplin way. Chaplin is template-agnostic.

And overall it depends on tpl lang you are using.

Mathias Schäfer

unread,
Oct 29, 2013, 5:44:36 AM10/29/13
to chapl...@googlegroups.com
Am 28.10.13 12:57, schrieb Charles Davison:
> I'm using the standard underscore templating library. What's the
> 'Chaplin' way of adding render helpers that can be access from within a
> template? E.g. formatDate(), etc.?

Chaplin doesn�t have strong conventions for that since they would depend
on the templating language used. There�s just the convention of
providing View::getTemplateFunction.

For example, the boilerplate is using Handlebars. Handlebars allows to
register view helpers:
https://github.com/chaplinjs/chaplin-boilerplate/blob/master/coffee/views/base/view.coffee
https://github.com/chaplinjs/chaplin-boilerplate/blob/master/coffee/lib/view-helper.coffee

_.template doesn�t allow to register helpers, but you can mix in your
helper functions into the data object. You can override
View::getTemplateData for that purpose. Example:

# require templateString and viewHelpers
class MyView extends Chaplin.View

getTemplateFunction: ->
# TODO: Caching the compiled template like in the boilerplate
_.template templateString

getTemplateData: ->
templateData = super
# Mix in your helpers
_.extend templateData, viewHelpers
templateData

viewHelpers should be a simple object with functions on it. It can be a
separate AMD/CommonJS module, like in the boilerplate.

There�s an article that described this technique, it�s also applicable
to Chaplin:
http://lostechies.com/derickbailey/2012/04/26/view-helpers-for-underscore-templates/

In Chaplin, you don�t have to override View::render, there�s
View::getTemplateData for this purpose.

Regards
Mathias
Reply all
Reply to author
Forward
0 new messages