cla*_*taq 5 html clojure compojure clojure-contrib
我是Clojure的新手,也是一个完整的HTML/Compojure处女.我正在尝试使用Compojure创建HTML的静态页面,使用类似于此的函数:
(defn fake-write-html
[dir args]
(let [file (str dir *file-separator* *index-file*)
my-html (html
(doctype :html4)
[:html
[:head
[:title "Docs and Dirs:"]]
[:body
[:div
[:h2 "A nice title"]]
[:div
[:ul
[:li "One"]
[:li "Two"]]]]])]
(clojure.contrib.duck-streams/spit file my-html)))
Run Code Online (Sandbox Code Playgroud)
该函数只是将HTML写入文件.(这里的args论点无关紧要.只是为了确保示例在我的程序中编译并运行.)
"Programming Clojure"表示对html函数的调用会生成格式化的HTML - 带缩进的多行.我得到的只是预期的doc类型,然后是一行中的所有HTML.HTML Tidy没有发现输出文件内容的任何问题.如果我println在REPL上它也会出现一条线.
是否需要其他东西才能获得格式化输出?
出于性能和复杂性的原因,删除了 Compojure中HTML输出的格式.要获得格式化输出,您可能需要编写自己的打印机功能.
我通常输出HTML,因为Compojure认为合适,并使用Firebug在我的浏览器中查看它.Firebug将显示格式很好,无论它是否真的都在一条线上.这在大多数情况下运作良好.如果你需要以可读的形式序列化这个HTML,你可以将它保存为Clojure向量和sexps并以这种方式序列化.
虽然Brian的回答把我指向Firebug,启用了我想要的调试,但我只是为了强迫它而不管它.按照kwertii指向JTidy的指针,我在程序中包含了以下代码.
编辑:稍微简化了代码
(ns net.dneclark.someprogram
(:gen-class)
...
(:import (org.w3c.tidy Tidy))
)
...
(defn configure-pretty-printer
"Configure the pretty-printer (an instance of a JTidy Tidy class) to
generate output the way we want -- formatted and without sending warnings.
Return the configured pretty-printer."
[]
(doto (new Tidy)
(.setSmartIndent true)
(.setTrimEmptyElements true)
(.setShowWarnings false)
(.setQuiet true)))
(defn pretty-print-html
"Pretty-print the html and return it as a string."
[html]
(let [swrtr (new StringWriter)]
(.parse (configure-pretty-printer) (new StringReader (str html)) swrtr)
(str swrtr)))
Run Code Online (Sandbox Code Playgroud)
我将jtidy-r938.jar添加到我的项目(NetBeans使用enclojure插件)并导入它.配置函数告诉解析器输出格式化的缩进HTML并跳过警告.不管是用Firebug还是简单的文本编辑器打开它,漂亮打印机功能的返回值现在都很好了.
| 归档时间: |
|
| 查看次数: |
3039 次 |
| 最近记录: |