Skip to content

Commit

Permalink
String html safety. Default to unsafe.
Browse files Browse the repository at this point in the history
  • Loading branch information
simon-nicholls committed Oct 3, 2012
1 parent 7ab1bb6 commit 07a4097
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 10 deletions.
5 changes: 5 additions & 0 deletions src/hiccup/compiler.clj
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,10 @@
[[_ condition & body]]
`(if ~condition ~@(for [x body] (compile-html x))))

(defmethod compile-form "list"
[[_ & body]]
`(apply str ~@(for [x body] (compile-html x))))

(defmethod compile-form :default
[expr]
`(#'render-html ~expr))
Expand Down Expand Up @@ -220,6 +224,7 @@
(doall (for [expr content]
(cond
(vector? expr) (compile-element expr)
(string? expr) (if (html-safe? expr) expr (escape-html expr))
(literal? expr) expr
(hint? expr String) expr
(hint? expr Number) expr
Expand Down
11 changes: 6 additions & 5 deletions src/hiccup/core.clj
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,12 @@
(defmacro html
"Render Clojure data structures to a string of HTML."
[options & content]
(if-let [mode (and (map? options) (:mode options))]
(binding [*html-mode* mode]
`(binding [*html-mode* ~mode]
~(apply compile-html content)))
(apply compile-html options content)))
(binding [*html-safe* #{}]
(if-let [mode (and (map? options) (:mode options))]
(binding [*html-mode* mode]
`(binding [*html-mode* ~mode]
~(apply compile-html content)))
(apply compile-html options content))))

(def ^{:doc "Alias for hiccup.util/escape-html"}
h escape-html)
17 changes: 12 additions & 5 deletions src/hiccup/util.clj
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
java.net.URLEncoder))

(def ^:dynamic *base-url* nil)
(def ^:dynamic *html-safe* #{})

(defmacro with-base-url
"Sets a base URL that will be prepended onto relative URIs. Note that for this
Expand Down Expand Up @@ -49,14 +50,20 @@
String
(to-uri [s] (URI. s)))

(defn html-safe [s]
(conj *html-safe* s)
s)

(def html-safe? *html-safe*)

(defn escape-html
"Change special characters into HTML character entities."
[text]
(.. ^String (as-str text)
(replace "&" "&")
(replace "<" "&lt;")
(replace ">" "&gt;")
(replace "\"" "&quot;")))
(html-safe (.. ^String (as-str text)
(replace "&" "&amp;")
(replace "<" "&lt;")
(replace ">" "&gt;")
(replace "\"" "&quot;"))))

(def ^:dynamic *encoding* "UTF-8")

Expand Down

0 comments on commit 07a4097

Please sign in to comment.