In CoffeeScript, is there an #39;official#39; way to interpolate a string at run-time instead of when compiled?(在 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'
这篇关于在 CoffeeScript 中,是否有一种“官方"方法可以在运行时而不是在编译时插入字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 CoffeeScript 中,是否有一种“官方"方法可以在运行时而不是在编译时插入字符串?


基础教程推荐
- 当用户滚动离开时如何暂停 youtube 嵌入 2022-01-01
- Karma-Jasmine:如何正确监视 Modal? 2022-01-01
- 动态更新多个选择框 2022-01-01
- 我什么时候应该在导入时使用方括号 2022-01-01
- 在for循环中使用setTimeout 2022-01-01
- 有没有办法使用OpenLayers更改OpenStreetMap中某些要素 2022-09-06
- 响应更改 div 大小保持纵横比 2022-01-01
- 悬停时滑动输入并停留几秒钟 2022-01-01
- 在 JS 中获取客户端时区(不是 GMT 偏移量) 2022-01-01
- 角度Apollo设置WatchQuery结果为可用变量 2022-01-01