如何将CSS放入字符串中?

时间:2013-05-20 14:41:56

标签: html css

我正在保存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;
}

2 个答案:

答案 0 :(得分: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>
    " )}

答案 1 :(得分: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

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

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”的类方法,AKA“IO.write”,它处理打开文件,写入内容并自动关闭它的中间步骤。