【问题标题】:How do I create a table for haml using loop directly in ruby file?如何直接在 ruby​​ 文件中使用循环为 haml 创建表?
【发布时间】:2015-11-24 16:44:08
【问题描述】:

我正在尝试创建一个显示 zip 文件内容的表格,如下所示:

Name      Size
asdf1.jpg 100KB
asdf2.jpg 200KB
asdf3.jpg 300KB

我的代码在这里(实际上,我是从 ZipRuby 的 README 中复制的):

#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)。)

【问题讨论】:

  • 你确定你使用的是Ruby on Rails吗?您能否确认您正在使用的 Web 框架?
  • 使用 Sinatra v1.4.6(与 Puma 一起)。感谢 cmets! :)

标签: ruby-on-rails ruby sinatra haml


【解决方案1】:

您可以通过为您的 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 的一些猜测工作 - 希望你明白必须做什么。

【讨论】:

    猜你喜欢
    • 2011-07-28
    • 1970-01-01
    • 1970-01-01
    • 2022-12-11
    • 2011-07-19
    • 1970-01-01
    • 1970-01-01
    • 2015-10-21
    • 1970-01-01
    相关资源
    最近更新 更多