在CoffeeScript中,是否有'官方'的方式来在运行时插入字符串而不是编译时?

问题描述:

我有一个选项在我的CS类的对象,我想保留一些模板是:在CoffeeScript中,是否有'官方'的方式来在运行时插入字符串而不是编译时?

class MyClass 
    options: 
     templates: 
      list: "<ul class='#{ foo }'></ul>" 
      listItem: "<li>#{ foo + bar }</li>" 
      # etc... 

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

是否有官方的CoffeeScript方式在运行时使用.replace()来做到这一点?


编辑:我最后写一个小工具,以帮助:

# interpolate a string to replace {{ placeholder }} keys with passed object values 
String::interp = (values)-> 
    @replace /{{ (\w*) }}/g, 
     (ph, key)-> 
      values[key] or '' 

所以我选择现在的样子:

templates: 
    list: '<ul class="{{ foo }}"></ul>' 
    listItem: '<li>{{ baz }}</li>' 

然后在后面的代码:

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

我想说,如果您需要延迟评估那么他们应该被定义为功能。

也许单独服用值:

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

鉴于你现在,前者的意见,你可以使用上面,像这样第二个例子:

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

感谢您的建议。 – Adam 2012-03-22 20:38:02

+0

再次感谢您的更新。你的解决方案看起来比我的'String :: interp'更干净。您的方式也会更好地执行,因为它不使用正则表达式或是一个非问题?我可能会在非常大的循环中做到这一点。 – Adam 2012-03-23 02:15:16

+0

对于任何可能会觉得这个有用的人来说,乔纳森的方法比我的执行得更好:http://jsperf.com/string-concat-vs-regex-replace – Adam 2012-03-26 23:40:25

相关推荐