如何将数组元素放入HTML表格?

时间:2012-12-24 22:22:19

标签: ruby

array = ["abc","mohasdan","321","324324"]
recipients = ["xxx@example.com"]
recipients_formatted = []
recipients.each {|s| recipients_formatted << "To: #{s}"}
message = <<MESSAGE_END
From: xxx@example.com <xxx@example.com>
#{recipients_formatted}

MIME-Version: 1.0
Content-type: text/html
Subject: Chef Report
<html>
<head>
<style type="text/css">
table {border-collapse:collapse;}
table, td, th {border:1px solid black;padding:5px;}
</style>
</head>
<body>
<h2>Chef Check-in Report</h2>
<p>
<p>
<table border=1>
<tr>
<th>Node</th>
<th>Time Since Last Check-in (Mins)</th>
</tr>
</table>
</body>
</html>
MESSAGE_END

Net::SMTP.start('localhost') do |smtp|
smtp.send_message message, 'xxx@example.com',
                           recipients
end

上面的代码会发送一封包含表格的电子邮件:

Chef  (column1)      |  Check-in Report(column2)   (row 1)  

我将数组内容放入要通过电子邮件发送的表中。 我希望第一行的第一列中的第一个数组元素,第一行的第二列中的第二个数组元素。 第二行第一列中的第三个数组元素,第二行第二列中的第四个数组元素,依此类推。

1 个答案:

答案 0 :(得分:5)

请尝试这样的事情:

custom_rows = ""
array.each_slice(2) do |row| 
  custom_rows << "<tr><td>#{row[0]}</td><td>#{row[1]}</td></tr>"
end

message#{custom_rows}

message = <<MESSAGE_END
From: xxx@example.com <xxx@example.com>
#{recipients_formatted}

MIME-Version: 1.0
Content-type: text/html
Subject: Chef Report
<html>
<head>
<style type="text/css">
table {border-collapse:collapse;}
table, td, th {border:1px solid black;padding:5px;}
</style>
</head>
<body>
<h2>Chef Check-in Report</h2>
<p>
<p>
<table border=1>
<tr>
<th>Node</th>
<th>Time Since Last Check-in (Mins)</th>
</tr>
#{custom_rows}
</table>
</body>
</html>