clojureenlive

Enlive templates – add to head section


Some pages of my app will have it's own js/css includes, so I wonder how I can add these resources to the head section of an html document with Enlive. I found "append" transformer, but there is no "html-append" without auto escaping. Or what a proper way to do that?


Solution

  • The other answers might predate enlive hiccup-style helpers. Answer taken and expanded from: Enlive templating - Adding CSS includes to <head>.

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

    Functions for generating HTML nodes (much much MUCH simpler):

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

    Example usage:

    ;; Example templates/base.html file    
    <html>
      <head>
      </head>
      <body>
      </body>
    </html>
    
    (def jquery "http://code.jquery.com/jquery-1.11.0.min.js") ; links work as well
    (html/deftemplate home-page "templates/base.html"
      []
       [:head] (html/append (map include-css ["css/some_file" "css/index.css"]))
       [:head] (html/append (map include-js [jquery "js/index.js"])))
    

    Check it produces the correct HTML:

    (print (apply str (home-page)))
    ;; newlines added by hand for clarity
    => <html>
         <head>
           <link href="css/some_file" rel="stylesheet" />
           <link href="css/index.css" rel="stylesheet" />
           <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
           <script src="js/index.js"></script>
         </head>
         <body>
         </body>
    
       </html>
       nil