I have an options object in my CS class, and I'd like to keep some templates in it:
class MyClass
options:
templates:
list: "<ul class='#{ foo }'></ul>"
listItem: "<li>#{ foo + bar }</li>"
# etc...
Then I'd like to interpolate these strings later in the code... But of course these are compiled to "<ul class='" + foo +"'></ul>"
, and foo is undefined.
Is there an official CoffeeScript way to do this at run-time using .replace()
?
Edit: I ended up writing a little utility to help:
# interpolate a string to replace {{ placeholder }} keys with passed object values
String::interp = (values)->
@replace /{{ (\w*) }}/g,
(ph, key)->
values[key] or ''
So my options now look like:
templates:
list: '<ul class="{{ foo }}"></ul>'
listItem: '<li>{{ baz }}</li>'
And then later in the code:
template = @options.templates.listItem.interp
baz: foo + bar
myList.append $(template)