在 CoffeeScript 中,是否有一种“官方"方法可以在运行时而不是在编译时插入字符串?

我的 CS 类中有一个选项对象,我想在其中保留一些模板:

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...

然后我想稍后在代码中插入这些字符串...但是当然这些被编译为 "<ul class='" + foo +"'></ul>",而 foo 是未定义的.

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.

是否有官方的 CoffeeScript 方法可以在运行时使用 .replace() 执行此操作?

Is there an official CoffeeScript way to do this at run-time using .replace()?

我最终编写了一个小实用程序来提供帮助:

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>'

然后在后面的代码中:

template = @options.templates.listItem.interp
    baz: foo + bar
myList.append $(template)

推荐答案

我想说,如果你需要延迟评估,那么它们可能应该被定义为函数.

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

也许单独取值:

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

或来自上下文对象:

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'

相关文章