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

霸气de小男生 提交于 2019-12-10 01:50:22

问题


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)

回答1:


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'


来源:https://stackoverflow.com/questions/9829470/in-coffeescript-is-there-an-official-way-to-interpolate-a-string-at-run-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!