In CoffeeScript, is there an 'official' way to interpolate a string at run-time instead of when compiled?

Adam picture Adam · Mar 22, 2012 · Viewed 8.6k times · Source

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)

Answer

Jonathan Lonowski picture Jonathan Lonowski · Mar 22, 2012

I'd say, if you need delayed evaluation, then they should probably be defined as functions.

Perhaps taking the values individually:

templates:
    list: (foo) -> "<ul class='#{ foo }'></ul>"
    listItem: (foo, bar) -> "<li>#{ foo + bar }</li>"

Or from a context object:

templates:
    list: (context) -> "<ul class='#{ context.foo }'></ul>"
    listItem: (context) -> "<li>#{ context.foo + context.bar }</li>"

Given your now-former comments, you could use the 2nd example above like so:

$(options.templates.listItem foo: "foo", bar: "bar").appendTo 'body'