-1

我正在保存一个 HTML 文件:

 <!DOCTYPE html>
        <html>
        <head>
        <title>'Previous Test Run Breakdown'</title>
        </head>
        <body>
            <h1> Breakdown of results by structure</h1>
            #{my_str}
        </body>
        </html>

my_str填写 HTML 页面的内容。里面my_str是我想要缩进的列表项。为此,我尝试在底部添加一个 CSS 标签以缩进所有li标签,例如:

 <!DOCTYPE html>
        <html>
        <head>
        <title>'Previous Test Run Breakdown'</title>
        </head>
        <body>
            <h1> Breakdown of results by structure</h1>
            #{my_str}
        </body>
        </html>
li {
    padding-left: 20px;
}

不幸的是,输出显示在页面上,而不是添加到底部作为li项目的填充:

li {
  padding-left: 20px;
}
4

2 回答 2

2

只需添加一个<style>标签:

File.open("features/output/all_test_breakdown.html", "w") { |file| file.write(
      " <!DOCTYPE html>
        <html>
        <head>
        <title>'Previous Test Run Breakdown'</title>
   <style>
    li {
        padding-left: 20px;
    }</style>
            </head>
            <body>
                <h1> Breakdown of results by structure</h1>
                #{my_str}
            </body>
            </html>
    " )}
于 2013-05-20T14:48:22.233 回答
1

啊。以下是如何更地道地写这个。从这个重写开始:

my_str = 'foo'
File.open("my_output.html", "w") do |file|
  file.write(<<EOT)
<!DOCTYPE html>
<html>
<head>
<title>'Previous Test Run Breakdown'</title>
</head>
<body>
    <h1> Breakdown of results by structure</h1>
    #{my_str}
</body>
</html>
EOT
end

我会使用以下方法进一步完善它:

my_str = 'foo'
File.write("my_output.html", <<EOT)
<!DOCTYPE html>
<html>
<head>
<title>'Previous Test Run Breakdown'</title>
</head>
<body>
    <h1> Breakdown of results by structure</h1>
    #{my_str}
</body>
</html>
EOT

如果在方法中粘贴“here-to”write会让您感到困惑,您可以这样做:

my_str = 'foo'
html = <<EOT
<!DOCTYPE html>
<html>
<head>
<title>'Previous Test Run Breakdown'</title>
</head>
<body>
    <h1> Breakdown of results by structure</h1>
    #{my_str}
</body>
</html>
EOT

File.write("my_output.html", html)

或者:

my_str = 'foo'
html = "
<!DOCTYPE html>
<html>
<head>
<title>'Previous Test Run Breakdown'</title>
</head>
<body>
    <h1> Breakdown of results by structure</h1>
    #{my_str}
</body>
</html>
"

File.write("my_output.html", html)

任何状况之下:

File.new("features/output/my_output.html", "w")
File.open("features/output/my_output.html", "w") { |file| file.write(
...

是代码气味。您不需要使用new来创建文件存根,然后open它后跟一个ios.write. 简直IO.write了。

如果您只是学习 Ruby,两者之间的区别似乎很难解读,但首先是写入文件句柄,AKA "ios" AKA "IO-stream"。第二个是“IO”的类方法,又名“IO.write”,它处理打开文件、写入内容和自动关闭文件的中间步骤。

于 2013-05-20T15:30:38.067 回答