html - String Replace Regex like mustache js for Ruby

标签 html ruby regex webrick

我是 ruby​​ 的新手,正在尝试制作一个简单的函数,该函数将获取一个文件并用一个数组替换所有的 mustache 。例如:

简单.tpl

<p>Hello {{person_name}}</p>
<p>{{welcome_msg}}</p>

我想用一组键和值来改变它。

class Template

    attr_accessor :file_name

    def parse_template (array_to_replace)
        str = File.read(file_name)

        array_to_replace.each do |item|
        # required code here ...
        end

        return str
    end

end

任何人都可以输入所需的代码吗???

预期输出

我不知道多维数组在 ruby​​ 中是如何工作的,但我想要的是:

the_arr = Array(
   :person_name => "John Doe",
   :welcome_msg => "Hello friend"
)
object = Template.new
object.file_name = "simple.tpl"
output = object.parse_template(the_arr);

puts output

我应该得到

<p>Hello John Doe</p>
<p>Hello friend</p>

最佳答案

您可以使用 the mustache gem :

require 'mustache'

attributes = {
  :person_name => "John Doe",
  :welcome_msg => "Hello friend"
}

template = File.read('simple.tpl')

output = Mustache.render(template, attributes)

puts output
# <p>Hello John Doe</p>
# <p>Hello friend</p>

关于html - String Replace Regex like mustache js for Ruby,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25663708/

相关文章:

ruby - ruby-1.9.2 和 ruby​​ 1.9.2-mri 与 rvm 的区别

javascript - 正则表达式查找大括号中的内容

regex - 为什么标点符号的 R gsub(或正则表达式)没有得到所有标点符号?

c# - 在表中查找 href 使用 Regex c#

html - HTML 源代码中 anchor 之间的新行在浏览器中创建空白区域

html - 可缩放视频不制作网格

javascript - 设置最大字数 HTML 文本框

ruby-on-rails - 多表排序

html - 网页顶部的空白过多

ruby - 轻松创建枚举器