在 CoffeeScript 中,是否有一种“官方"方法可以在运行时而不是在编译时插入字符串? [英] In CoffeeScript, is there an 'official' way to interpolate a string at run-time instead of when compiled?

查看:14
本文介绍了在 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 中,是否有一种“官方"方法可以在运行时而不是在编译时插入字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆