cssclojureenlive

Enlive templating - Adding CSS includes to <head>


I'm not sure how I should be approaching this. I have a list of CSS files that I want to feed into something and get HTML back. For example,

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

should be transformed into:

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

From there it should be appended into <head>.

defsnippet almost looks appropriate but takes a template file and a selector for a section of that file. The generated HTML here is not dependent on a template and something that only generates the HTML seems appropriate. clone-for might do the looping part of what I want but I'm having trouble figuring out how to use it.


Solution

  • Alternatively:

    (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 ()})
    

    Double-check it produces the correct 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