Fast library for rendering HTML in Clojure Hiccup 1.0.5 API documentation

How can I parse string into Hiccup?

How can I parse a string of Hiccup into a Hiccup node?

For example, "[:b 'hello world']" into [:b "hello world"]

Source: (StackOverflow)

Automatically escaping HTML with Hiccup, is it possible?

I just tried this with Hiccup:

(hiccup.core/html [:h1 "<script>alert('xss');</script>"])

and to my surprise I got an alert box, Hiccup is not escaping strings by default. I see that there's a method to escape strings, but in my opinion if it's not the default, sooner or later you'll forget and be vulnerable to XSS.

Is there a way in Hiccup to have it escape strings by default?

Source: (StackOverflow)


CSS fails with extended paths in Compojure / Hiccup

I've been converting some Noir websites to Compojure.

I have a function here that creates the layout of the page:

(defn layout [title & content]
    [:title "My Site | " title]
    (include-css "css/main.css")
     [:h1 (link-to "/" "My Site")]]

And this is the function and the routes:

(defn home-page []
   [:div [:p "Home Page"]])))

(defn article-list []
   "Article List"
   [:div [:p "Article List"]])))

(defroutes app-routes
  (GET "/" [] (home-page))
  (GET "/article-list" [] (article-list))

When I open up localhost:3000/article-list all of the CSS rules work fine.

However, when I attempt to extend the URL path and change the program to:

(defn article-list []
   "Article List"
   [:div [:p "Article List"]])))

(defn article-one []
   "Article One"
   [:div [:p "Article One"]])))

(defroutes app-routes
  (GET "/" [] (home-page))
  (GET "/article-list" [] (article-list)
  (GET "/article-list/article-one" [] (article-one))

And go to localhost:3000/article-list/article-one, I get all of the HTML but the CSS rules no longer work. When I inspect the page, the css paths are included in the < head > element but there are no styles on the page.

I've searched for a solution to this issue, but there doesn't seem to be any writing on this. I've also tried pulling out the routes so that I have:

(defroutes article-routes
  (GET "/article-list/article-one" [] (article-one))

(defroutes app-routes
  (GET "/" [] (home-page))
  (GET "/article-list" [] (article-list)
  (context "article-list" [] article-routes)

but I have the same issue. How can I get the CSS rules to work on pages with extended paths?

Source: (StackOverflow)

Clojure use of (for) with hiccup and noir

I am using clojure and hiccup (with noir) and I have this code:

(defn dataframe [id]
   (db/db-to-data id))

(defpartial drop-downs [nms]
  (for [nm (keys nms)] (drop-down nm (get nms nm))[:br])
  (submit-button "Refresh")  

(defpage "/dataset/table/:id" {:keys [id]}
    (form-to [:post (format "/dataset/table/%s" id)]
      (drop-downs {"alessio" [:col0], "test" [:col1]})
   (html-table (dataframe id))))

My problem is with:

(for [nm (keys nms)] (drop-down nm (get nms nm))[:br])

I want to have multiple select in my form. The line above does that, but for some reason it does not consider [:br], so it does not break the lines. However, if I do this:

(form-to [:post (format "/dataset/table/%s" id)]
      (drop-down "Test1" "1")[:br]
      (drop-down "Test2" "2")[:br]

The [:br] tag does work. I believe this is connected with how the (for) macro works, but I could not figure out the reason and how to fix it.


As advised, I dropped the use of for. Final result below (which is Joost answer with a slight mod):

(mapcat #(vector (drop-down % (nms %)) [:br]) (keys nms))

Source: (StackOverflow)

Idiomatic way of rendering style info using Clojure Hiccup

I need to build style info within hiccup in order to place an element at a location indicated by the variables "top" and "left". My code looks like so:

(html [:div {:style (str "top" top ";left" left)} "some text"])

This code is pretty ugly. It would be nicer if hiccup automatically rendered the "style" attribute using standard CSS style rules... Then I could write the following:

(html [:div {:style {:top top :left left}} "some text"])

Is there already a library that does this? Or, do I need to roll my own solution?

Thank you Clojurians for any pointers!

Source: (StackOverflow)

Using Compojure, Hiccup and Ring to upload a file

To upload a file to a server I'm writing in Clojure I need a client form that looks something like this:

<form action="/file" method="post" enctype="multipart/form-data">
<input name="file" type="file" size="20" />
<input type="submit" name="submit" value="submit" />

However I can't find the documentation for Hiccup or in Compojure to create a form like this. The sample I have looks like this :

[:h2 "Choose a file to upload"]
:form {:method "post" :action "/upload"}
[:input.math {:type "text" :name "a"}] [:span.math " + "]
[:input.math {:type "text" :name "b"}] [:br]

So my question is where is the documentation to find how this should be modified to make a form that will upload a file?

Source: (StackOverflow)

Clojure: zipper -> html

After a few days of trying to wrap my brain around zippers, I think I finally understand how to create them from sequential data.

However, after searching for a few days, I can't seem to find any resources on how convert a zipper into something else. Basically, I want to convert some data into a format that I can pass to Hiccup to generate some HTML.

Are there any good resources on what I should be doing to convert a zipper tree into a different data structure?

Source: (StackOverflow)

EOF exception while reading clojure file

When I run the web application in the ring jetty server, I got EOF exception, I can't fix this, since there is no clue on which line the error has occurred. I'm using compojure and hiccup on my clojure code. I'm using Emacs 23 as editor.

Here is the part of the exception :

Exception in thread "main" java.lang.Exception: EOF while reading (core.clj:66)
        at clojure.lang.Compiler.load(Compiler.java:5863)
        at clojure.lang.RT.loadResourceScript(RT.java:340)
        at clojure.lang.RT.loadResourceScript(RT.java:331)

How can I fix it? Thanks!

Source: (StackOverflow)

Clojure: Dynamically create functions from a map -- Time for a Macro?

I have a function that begins like this:

(defn data-one [suser]
    (def suser-first-name
       (select db/firstNames
            (fields :firstname)
            (where {:username suser})))
    (def suser-middle-name
        (select db/middleNames
            (fields :middlename)
            (where {:username suser})))
    (def suser-last-name
         (select db/middleNames
             (fields :lastname)
             (where {:username suser})))
    ;; And it just continues on and on...

Of course, I don't like this at all. I have this pattern repeating in many areas in my code-base and I'd like to generalize this.

So, I came up with the following to start:

(def data-input {:one '[suser-first-name db/firstNames :firstname] 
                      '[suser-middle-name db/middleNames :middlename]
                      '[suser-last-name db/lastNames :lastname]})

(defpartial data-build [data-item suser]
    ;; data-item takes the arg :one in this case
     `(def (data-input data-item)
        (select (data-input data-item)
            (fields (data-input data-item))
            (where {:username suser}))))

There's really a few questions here:

-- How can I deconstruct the data-input so that it creates x functions when x is unknown, ie. that the values of :one is unknown, and that the quantities of keys in data-input is unknown.

-- I'm thinking that this is a time to create a macro, but I've never built one before, so I am hesitant on the idea.

And to give a little context, the functions must return values to be deconstructed, but I think once I get this piece solved, generalizing all of this will be doable:

(defpage "/page-one" []
    (let [suser (sesh/get :username)]       
    (data-one suser)
        [:p "Firat Name: " 
            [:i (let [[{fname :firstname}] suser-first-name]
                (format "%s" fname))]
        [:p "Middle Name: "  
            [:i (let [[{mname :emptype}] suser-middle-name]
                (format "%s" mname))]
        [:p "Last Name: " 
            [:i (let [[{lname :months}] suser-last-name]
                    (format "%s" lname))]]))

Source: (StackOverflow)

Composing templates with Hiccup and Compojure

I'm relatively new to Clojure and Compojure web development. The first issue that I've noticed in the toy example that I'm building is that of HTML templating. I'd like to have support for something like partials in Rails, or the templating framework that Django uses.

Currently I have:

(defn index-page []
        [:title "Home | Compojure Docs"]
        (include-css "/css/bootstrap.min.css")
        (include-css "/css/bootstrap-responsive.min.css")]
        [:div {:class "container-fluid"}
            [:div {:class "row-fluid"}
                [:div {:class "span2 menu"}]
                [:div {:class "span10 content"}
                    [:h1 "Compojure Docs"]
                            [:a {:href "/getting-started"} "Getting Started"]]
                            [:a {:href "/routes-in-detail"} "Routes in Detail"]]
                            [:a {:href "/destructuring-syntax"} "Destructuring Syntax"]]
                            [:a {:href "/nesting-routes"} "Nesting Routes"]]
                            [:a {:href "/api-documentation"} "API Documentation"]]
                            [:a {:href "/paas-platforms"} "PaaS Platforms"]]
                            [:a {:href "/example-project"} "Example Project"]]
                            [:a {:href "/example-project-on-cloudbees"} "Example Project on CloudBees"]]
                            [:a {:href "/interactive-development-with-ring"} "Interactive Development with Ring"]]
                            [:a {:href "/emacs-indentation"} "Emacs Indentation"]]
                            [:a {:href "/sessions"} "Sessions"]]
                            [:a {:href "/common-problems"} "Common Problems"]]]
                    (include-js "/js/jquery-1.9.1.min.js")
                    (include-js "/js/bootstrap.min.js")]]]]))

(defn routes-in-detail []
        [:title "Routes in Detail | Compojure Docs"]
        (include-css "/css/style.css")]
        [:h1 "Routes in Detail"]]))

Is there a good way for me not to repeat code? I'd like the stuff in the HEAD tag to be in it's own template file or function, and then be able to include it as I go. For instance, I'd like to include it in the 'routes-in-detail' function. I've looked at Enlive, but I'm not sure how to use that with Hiccup. Any thoughts on best practices here would be appreciated.

Source: (StackOverflow)

Change a div color in hiccup

Is there a way I can set a div background color in hiccup? Here is what I tried so far, with no result:

[:div {:background-color "#003366"} (escape-html rest)]

In the html, I see <div background-color="#663366"> which I do not believe is the correct format for color.

Is there a way to do this in hiccup?

Source: (StackOverflow)

Pagination in Clojure

Is there anything equivalent to will_paginate for noir/hiccup?

How do people usually paginate with noir/hiccup?

Thank you

Source: (StackOverflow)

How to display {} in hiccup?

I am working on an angular app, where I need to display some angular expression in this form:

{{"Hello," name}}

In Hiccup, {} have a special meaning, and is used for attributes, how to use it for angular syntax ?

Source: (StackOverflow)

Parsing a clojure map of items -> categories-vectors into categorized lists

I have map of item names and vectors of vectors which store categories which the key string item are in. I am trying to parse this map into a couple hiccup defpartials which then can display them organized by category.

What I think I need to do is parse the map once to make a set of all possible categories and sub categories. Once I have that I can iterate that and filter all matches from the main map to get the proper key strings.

How can I go from the map below, to a set of all main and sub categories? Once I have that set, how do i use it query the original map by values not by key?

thanks for any help!

 { "thingy"          [["CatergoryA" "SubcategoryA"]]
   "thingy2"         [["FFT"]]
   "thingy3"         [["Generators" "Chaotic"]]
   "thingy4"         [["Analysis" "Pitch"] ["MachineListening"]]
   "thingy5"         [["Multichannel" "Ambisonics"]]

goal in sudo code

(generate-hiccup-partial (create-set-of-unique-categories ITEM-CATEGORIES) ITEM-CATEGORIES)
(defpartial generate-hiccup-partial
  [categories map]
   ;; hiccup code
   (in-each-sub/main-category-get-keys-by-value categories map))  ;; return a list of all keys with the same categories

Source: (StackOverflow)

hiccup code not responding without (do (html5 at each level

I am not able to run inner [:tr] without (do (html5 ..)) when i am using nested let statement having for loop.

(defpartial column-settings-layout [& content]

     [:title "my-noir-proj"]
            (include-css "assets/css/bootstrap.css")
      [:image {:src "assets/img/ceva.gif" :alt "ceva-logo"}]
     [:div {:style "overflow: auto; overflow-x: hidden"}
      [:form {:id "col_settings_form" :name "col_settings_form" :method="post" :enctype="multipart/form-data"}
       [:input {:type "button" :value "Save" :onclick "ajaxWithSerialize('save_cols_response_div','/save_cols_settings',$(col_settings_form).serialize());"}]
       [:table {:class "table-striped" :border "1"}

            [:tr [:td {:id "processing_status" }  ][:td {:id "save_cols_response_div" :colspan 6}  ]]
            [:tr [:td ][:td {:colspan "3"} "SP" ] [:td {:colspan "3"} "WP"]]
            (let [wp_settings (session/get :wp_settings)
                 sp_settings (session/get :sp_settings)]

                (do (html5 [:tr [:td {:colspan "7"} "jhyghjghj"]]))
                    (for [col (:all_cols (session/get :setting_doc))]
                         dest_station (keyword (session/get :dest_station))
                         ;col_nm  (:col_nm (nth col 1))
                         field_nm  (nth col 0)                   
                         sp_col_nm (:col_nm (field_nm (dest_station sp_settings)))
                         wp_col_nm (:col_nm (field_nm (dest_station wp_settings)))                                
                         sp_editable (:editable (field_nm (dest_station sp_settings)))
                         wp_editable (:editable (field_nm (dest_station wp_settings)))

                        (do (html5 [:tr[:td "sfsdfgfds"]] 
                           [:th { :align "right"  :class "input-small" } field_nm ] 
                           [:td {:title sp_editable }[:input {:type "text" :class "input-large" :name (str "page_sp[" dest_station "][" field_nm "][col_nm]")  :value sp_col_nm } ] ] 
                           [:td [:input {:type "checkbox" :name (str "page_sp[" dest_station "][" field_nm "][col_nm]") :value field_nm}]]
                         [:td [:input {:type "checkbox" :name (str "page_sp[" dest_station "][" field_nm "][editable]") :value field_nm}]]
                         [:td {:title wp_editable }[:input {:type "text" :class "input-large" :name (str "page_wp[" dest_station "][" field_nm "][col_nm]")  :value wp_col_nm} ] ] 
                           [:td [:input {:type "checkbox" :name (str "page_wp[" dest_station "][" field_nm "][col_nm]") :value field_nm}]] 
                         [:td [:input {:type "checkbox" :name (str "page_wp[" dest_station "][" field_nm "][editable]") :value field_nm}]]


    ;my includes of js and css

Source: (StackOverflow)