在CoffeeScript中,是否有“正式"方式在运行时而不是在编译时内插字符串? [英] In CoffeeScript, is there an 'official' way to interpolate a string at run-time instead of when compiled?
问题描述
我在CS类中有一个options对象,我想在其中保留一些模板:
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.
在运行时是否有使用.replace()
的官方CoffeeScript方法?
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'
这篇关于在CoffeeScript中,是否有“正式"方式在运行时而不是在编译时内插字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!