我正在尝试创建一个表,该表显示zip文件的内容,如下所示:
Name Size
asdf1.jpg 100KB
asdf2.jpg 200KB
asdf3.jpg 300KB
我的代码在这里(实际上,我是从zipruby的自述文件中复制的):
#myapp.rb
post 'checkfile/?' do
Zip::Archive.open('zip_file.zip') do |ar|
n = ar.num_files
n.times do |i|
entry_name = ar.get_name(i) # get entry name from archive
# open entry
ar.fopen(entry_name) do |f| # or ar.fopen(i) do |f|
$name = f.name # name of the file
$size = f.size # size of file (uncompressed)
$comp_size = f.comp_size # size of file (compressed)
content = f.read # read entry content
end
end
# Zip::Archive includes Enumerable
entry_names = ar.map do |f|
f.name
end
end
haml :checkresult
end
还有我的haml代码:
-# checkresult.haml
%table
%thead
%tr
%th Name
%th Size
%tbody
%tr
-# I want to show files in zip here
对不起,英文不好,标题也不好。
(使用Sinatra v1.4.6(带彪马)
最佳答案
通过将值分配给Sinatra应用程序中的实例变量,可以传递haml
渲染的数据请通过this tutorial。
您需要对myapp.rb
进行一些更改,如下所示我们定义@result
数组来收集结果
# myapp.rb
post 'checkfile/?' do
@result = [] # this will hold results.
Zip::Archive.open('zip_file.zip') do |ar|
ar.each do |f|
@result << [f.name, f.size, f.comp_size]
end
end
haml :checkresult
end
您将需要更新您的haml文件,如下所示-
table
添加标记,添加迭代器以迭代结果并发出td
-# checkresult.haml
%table
%thead
%tr
%th Name
%th Size
%th Compressed size
%tbody
%table
- @result.each do |i|
%tr
%td= i[0]
%td= i[1]
%td= i[2]
注:我无法在我的Windows机器上安装ZipRuby,因此上面的部分代码是基于documentation的猜测工作-希望您知道必须做什么。
关于ruby-on-rails - 如何直接在ruby文件中使用循环为haml创建表?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32297851/