我是 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/