简单的Ruby模板引擎

时间:2015-01-03 20:57:39

标签: ruby templates web

我尝试在Ruby中编写一个简单的Web模板引擎,它接受输入,JSON文件并生成HTML文件。要替换的内容将使用类似<* place_holder *>的语法。

例如,模板如下所示:

<body>    
<* EACH students student *>
  <* student.name *>
  <* EACH student.nicknames nickname *>
    <p><* nickname *></p>
  <* ENDEACH *>    
<* ENDEACH *>
</body>

JSON是:

   {
  "page": {
    "title": "Templating Example"
  },
  "teacher": {
    "name": "Mr. John"
  },
  "students": [
    { "name": "Bruce Wayne", "nicknames": ["Batman"] },
    { "name": "Peter Parker", "nicknames": ["Spidey", "Spiderman", "Spider-Man"] }
  ]
}

,输出结果为:

<body>
<h1>Mr. John</h1>

  Bruce Wayne

    <p>Batman</p>


  Peter Parker

    <p>Spidey</p>

    <p>Spiderman</p>

    <p>Spider-Man</p>

我有什么:

def replace_loop(lop_arr,json_data,somefile)

regex = Regexp.new(/\<\* .* \*\>/)      


lop = false
key = ""
size_lop = 0
length = lop_arr.size - 1   

for i in 0..length # go line by line 
  # check if it is loop indicator, replace with blank
  if lop_arr[i].include?("<* EACH") 
    lop = true
    new_content = lop_arr[i].gsub(lop_arr[i], "")
    somefile.puts new_content

   # check if it is endloop indicator, replace with blank
  elsif lop_arr[i].include?("<* ENDEACH")
    new_content = lop_arr[i].gsub(lop_arr[i], "")
    somefile.puts new_content
    lop = false
  else
    if lop # if inside the loop
      blank = lop_arr[i].gsub(regex, "")
      somefile.puts blank   
      # separate the content to find value in JSON data                 
      replacement = lop_arr[i].match(regex)
      replacement_content = replacement.to_s.match(/ .* /).to_s.strip
      arr_data = replacement_content.split(".")  
       # arr_data:   [student, name]
      arr_data_length = arr_data.length - 1
      data = ""
      # because the JSON file contains the plural of the object, so I use pluralzie to find the    value
      json_data[arr_data.first.pluralize].each do |ele|
        for j in 1..arr_data_length
            data = ele[arr_data[j]]
            puts data
        end
        somefile.puts data
      # somefile.puts "\n"
      end
    end
  end

这只会打印出所有学生的名字,我不知道如何更换内圈以放置学生的昵称

0 个答案:

没有答案