13

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)
Adam
  • 3,061
  • 4
  • 21
  • 27

1 Answers1

22

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'
Jonathan Lonowski
  • 112,514
  • 31
  • 189
  • 193
  • Thanks again for the update. Your solution looks a little cleaner than my `String::interp` thing. Would your way also perform better because it doesn't use regex or is that a non-issue? I may be doing this in very large loops. – Adam Mar 23 '12 at 02:15
  • For anyone else who may find this useful, Jonathan's method performs much better than mine: http://jsperf.com/string-concat-vs-regex-replace – Adam Mar 26 '12 at 23:40