1

我不确定我应该如何处理这个问题。我有一个 CSS 文件列表,我想将这些文件输入某些内容并获取 HTML。例如,

(list "base.css" "index.css" "more_css.css") ;vector might be more appropriate?

应转化为:

<link href="css/base.css" rel="stylesheet" />
<link href="css/index.css" rel="stylesheet" />
<link href="css/more_css.css" rel="stylesheet" />

从那里它应该被附加到<head>.

defsnippet几乎看起来合适,但需要一个模板文件和该文件的一部分的选择器。这里生成的 HTML 不依赖于模板,只生成 HTML 的东西似乎很合适。clone-for可能会做我想要的循环部分,但我无法弄清楚如何使用它。

4

2 回答 2

5

defsnippet实际上采用 Enlive 可以理解的任何来源,它不需要是文件。特别是,它可以是link标签模板的内联 Enlive 样式表示。从 1.1.0 版本开始,Enlive 还提供了一个帮助器 ( net.grand.enlive-html/html) 来解析 Hiccup 样式符号;我发现打嗝式手写更方便,所以我将在下面使用它。(您还可以通过将内联 HTML 字符串包装在StringReader:中来使用它们(java.io.StringReader. "<div></div>")。)

这是代码:

(require '[net.cgrand.enlive-html :as enlive])

(enlive/defsnippet link-css
  ;; representation of the link tag template:
  (enlive/html [:link {:href "" :rel "stylesheet"}])
  ;; selector is required, :link works fine here:
  [:link]
  ;; this is the parameter vector of the fn defsnippet will generate:
  [hrefs]
  ;; clone-for will generate one link tag for each provided href:
  (enlive/clone-for [href hrefs]
    [:link]
    (enlive/set-attr :href href)))

你会像这样使用它:

(->> (link-css ["css/base.css" "css/index.css" "css/more_css.css"])
  (enlive/emit*)
  (apply str))
;= "<link href=\"css/base.css\" rel=\"stylesheet\" /><link href=\"css/index.css\" rel=\"stylesheet\" /><link href=\"css/more_css.css\" rel=\"stylesheet\" />"

添加println->>管道的末尾是一种方便的测试方法;这是输出(为清楚起见,手动插入了两个换行符):

<link href="css/base.css" rel="stylesheet" />
<link href="css/index.css" rel="stylesheet" />
<link href="css/more_css.css" rel="stylesheet" />
于 2013-12-28T16:43:34.473 回答
0

或者:

(require '[net.cgrand.enlive-html :as enlive])

(defn include-css [href]
      (first (enlive/html [:link {:href href :rel "stylesheet"}])))

(map include-css ["css/base.css" "css/index.css" "css/more_css.css"])
;; newlines added by hand for clarity
=> ({:tag :link, :attrs {:href "css/base.css", :rel "stylesheet"}, :content ()} 
    {:tag :link, :attrs {:href "css/index.css", :rel "stylesheet"}, :content ()} 
    {:tag :link, :attrs {:href "css/more_css.css", :rel "stylesheet"}, :content ()})

仔细检查它是否生成正确的 HTML:

(print (apply str (html/emit* (map include-css ["css/base.css" "css/index.css" "css/more_css.css"]))))
;; newlines added by hand for clarity
=> <link href="css/base.css" rel="stylesheet" />
   <link href="css/index.css" rel="stylesheet" />
   <link href="css/more_css.css" rel="stylesheet" />
   nil
于 2014-01-30T04:28:43.560 回答