我有一个如下所示的字符串模板
template = '<p class="foo">#{content}</p>'
我想根据名为 content
的变量的当前值评估模板。
html = my_eval(template, "Hello World")
这是我目前解决这个问题的方法:
def my_eval template, content
"\"#{template.gsub('"', '\"')}\"" # gsub to escape the quotes
end
有没有更好的方法来解决这个问题?
编辑
我在上面的示例代码中使用了 HTML 片段来演示我的场景。我的真实场景在配置文件中有一组 XPATH 模板。替换模板中的绑定(bind)变量以获得有效的 XPATH 字符串。
我曾考虑过使用 ERB,但最终还是放弃了,因为它可能有点矫枉过正。
最佳答案
您可以使用 String 的本地方法 '%' 做您想做的事:
> template = "<p class='foo'>%s</p>"
> content = 'value of content'
> output = template % content
> puts output
=> "<p class='foo'>value of content</p>"
关于ruby-on-rails - 评估字符串模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2321428/