【问题标题】:Scala NodeSeq reduce/foldLeft with newlinesScala NodeSeq reduce/foldLeft 带换行符
【发布时间】:2012-04-28 06:25:01
【问题描述】:

假设这很简单,但很难用换行符打印出 html 标签的 NodeSeq(所以当我在 Web 浏览器中查看源代码时,我可以从上到下扫描)

按原样,NodeSeq 打印为一长行。

示例代码:

listOfPaths map ( jsNode(_) ) reduce (_++_)

def jsNode(path: String): NodeSeq =
  <script type="text/javascript" src={"/static/js/"+path}></script>

那么,如何在每个节点的末尾得到一个\n

谢谢

【问题讨论】:

    标签: scala newline reduce xmlnode


    【解决方案1】:

    无论您使用什么来呈现 HTML,这都是一项真正的工作。例如,如果你使用scala.xml.PrettyPrinter,你可以这样做:

    val printer = new xml.PrettyPrinter(80, 2)
    val paths = List("script-1.js", "script-2.js")
    val header = <head>{paths map ( jsNode(_) ) reduce (_++_)}</head>
    

    现在当您拨打printer.format(header) 时,您将收到以下信息:

    <head>
      <script type="text/javascript" src="/static/js/script-1.js"></script>
      <script type="text/javascript" src="/static/js/script-2.js"></script>
    </head>
    

    请注意,PrettyPrinter 构造函数的第一个参数指定页面宽度,第二个参数指定缩进的空格数。

    如果你只是想要一些快速而肮脏的东西,你可以在元素之间(或之后)放置一个文本节点:

    paths map ( jsNode(_) ) reduce (_++ Text("\n") ++ _)
    

    但其他解决方案几乎总是更可取。

    【讨论】:

    • 谢谢,后者,又快又脏,现在可以解决问题:只想快速直观地解析输出,在生产中,google mod_pagespeed 会将整个源 html 压缩成 1 长不可读的行; -)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-04
    • 1970-01-01
    • 2013-03-07
    • 2014-09-29
    • 1970-01-01
    • 2011-05-09
    相关资源
    最近更新 更多