Fast library for rendering HTML in Clojure Hiccup 1.0.5 API documentation

how to return a clojure function as a string

is there any way to return a clojure function as a string? I am making some online documentation and I would really like to be able to add code into the html by somehow evaluating a function into text.


Source: (StackOverflow)

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)

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)

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)

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: 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)

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)

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)

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)

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/compojure/hiccup NullPointerException

The stack trace I have does not contain any reference to my code. I'm not sure how to begin finding out what might be wrong here:

LazySeq.java:47 clojure.lang.LazySeq.sval
LazySeq.java:56 clojure.lang.LazySeq.seq
Cons.java:39    clojure.lang.Cons.next
RT.java:560 clojure.lang.RT.next
core.clj:61 clojure.core/next
core.clj:461    clojure.core/str$fn[fn]
core.clj:463    clojure.core/str
RestFn.java:140 clojure.lang.RestFn.applyTo
core.clj:540    clojure.core/apply
core.clj:90 hiccup.core/eval460$fn[fn]
MultiFn.java:163    clojure.lang.MultiFn.invoke
Var.java:365    clojure.lang.Var.invoke
stacktrace.clj:26   ring.middleware.stacktrace/html-ex-view
stacktrace.clj:40   ring.middleware.stacktrace/html-ex-response
stacktrace.clj:51   ring.middleware.stacktrace/ex-response
stacktrace.clj:61   ring.middleware.stacktrace/wrap-stacktrace$fn[fn]
reload_modified.clj:15  ring.middleware.reload-modified/wrap-reload-modified$fn[fn]
stacktrace.clj:59   ring.middleware.stacktrace/wrap-stacktrace$fn[fn]
jetty.clj:17    ring.adapter.jetty/proxy-handler$fn[fn]
(Unknown Source)        ring.adapter.jetty.proxy$org.mortbay.jetty.handler.AbstractHandler$0.handle
HandlerWrapper.java:152 org.mortbay.jetty.handler.HandlerWrapper.handle
Server.java:324 org.mortbay.jetty.Server.handle
HttpConnection.java:534 org.mortbay.jetty.HttpConnection.handleRequest
HttpConnection.java:879 org.mortbay.jetty.HttpConnection$RequestHandler.content
HttpParser.java:741 org.mortbay.jetty.HttpParser.parseNext
HttpParser.java:213 org.mortbay.jetty.HttpParser.parseAvailable
HttpConnection.java:403 org.mortbay.jetty.HttpConnection.handle
SocketConnector.java:228    org.mortbay.jetty.bio.SocketConnector$Connection.run
QueuedThreadPool.java:522   org.mortbay.thread.QueuedThreadPool$PoolThread.run

This happens after a form submit--the controller writes a record to the db and redirects to the page:

(defn create-submit [& m]
  (let [p (model/create m)]
      (response/redirect (str "/post/" (:id p)))))

I see hiccup in the stack trace but there is no page rendering going on here. And the browser still points to the original page, not the redirected page, so I'm thinking that the redirect never happens.



With some println's I've tracked it down to the model/create call, which is calling clojureql to conj! the new record. The first println shows up in the console window and the second doesn't.

(defn create [m] 
    (let [p (new-post-from m)] 
        (println "about to add p to table " (:id p)) 
        (cql/conj! (cql/table :posts) p)
        (println "after adding p to table")

Source: (StackOverflow)

How can I pass edn to clojurescript from clojure without making ajax request (i.e. via hiccup-generated page)

I'm developing RIA with clojure and clojurescript. Backend uses hiccup to generate a resulting html, like

  (include-js "/js/my-cljs-generated.js")]
[:body ... ])

How can I pass edn(hashmap, vector, etc.) to clojurescript within the resulting html, i.e. without doing ajax call?

I would like to make hiccup do something like this:

   "var_name" {:foo :bar}) ; or any other clojure data

and to be able to access the passed edn from cljs somehow(e.g. by name).

Currently my implementation is a bit hacky and stores edn in a global js var

(hiccup/javascript-tag (str "var edn = \""
                       (pr-str my-clojure-data) "\";"))        

and on cljs side does smth like

  (fn []
    (if-let [edn (.-edn js/window)]
      (do-something-with (cljs.reader/read-string edn))

Maybe there is more idiomatic way of achieving this?

Source: (StackOverflow)

How to convert HTML tag with style to Hiccup? React problems

I'm trying to parse HTML with CSS into Hiccup in a Reagent project. I am using Hickory. When I parse HTML with inline CSS, React throws an exception.

         as-hiccup (parse-fragment "<div style='color:red'>test</div>")

The above generates [:div {:style color:red} "test"] & Reactjs returns exception from Reactjs:

Violation: The style prop expects a mapping from style properties to values, not a string.

I believe [:div {:style {"color" "red"}} "test"] must be returned instead.

Here is the code view:

(ns main.views.job
  (:require [reagent.core :as reagent :refer [atom]]
                    [hickory.core :refer [as-hiccup parse parse-fragment]]))


(defn some-view [uid]
     (map as-hiccup (parse-fragment "<div style='color:red'>test</div>"))   

Source: (StackOverflow)

hiccup form-helper with compojure

Exception: Exception in thread "main" java.io.FileNotFoundException: Could not locate hiccup/form_helpers__init.class or hiccup/form_helpers.clj on classpath:

I'm trying to get a toy compojure app up and running. The original app was from CloudBees and their ClickStart app for Clojure/Compojure. I'm trying to add a simple form (that won't persist anything yet) using hiccup form_helpers but I'm getting a ClassNotFound exception. Here's what I've done:


(defproject mywebapp "0.1.0-SNAPSHOT"
:description "FIXME: write description"
:url "http://example.com/FIXME"
:dependencies [[org.clojure/clojure "1.4.0"]
             [compojure "1.1.1"]
             [hiccup "1.0.1"]]
:plugins [[lein-ring "0.7.3"]]
:ring {:handler mywebapp.routes/app}
{:dev {:dependencies [[ring-mock "0.1.3"]]}})


(ns mywebapp.views
(:use [hiccup core page]
    [hiccup form-helpers :only [form-to label text-area submit-button]]))
(defn shout-form []
[:div {:id "shout-form" }
 (form-to [:post "/form"]
        (label "shout" "What do you want to SHOUT?")
        (text-area "shout")
        (submit-button "SHOUT!"))])

Source: (StackOverflow)