如何直接在 ruby 文件中使用循环为 haml 创建 table?
How do I create a table for haml using loop directly in ruby file?
我正在尝试创建一个 table 来显示 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(带 Puma。))
您可以通过为 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]
PS:我无法在我的 Windows 机器上安装 ZipRuby,所以上面的部分代码是基于 documentation 的一些猜测工作 - 希望你明白必须做什么。
我正在尝试创建一个 table 来显示 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(带 Puma。))
您可以通过为 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]
PS:我无法在我的 Windows 机器上安装 ZipRuby,所以上面的部分代码是基于 documentation 的一些猜测工作 - 希望你明白必须做什么。