Skip to content
Browse files

String html safety. Default to unsafe.

  • Loading branch information...
1 parent 7ab1bb6 commit 07a4097b1c4433d72235e19d7a22203fed6c2e85 @simon-nicholls committed Oct 3, 2012
Showing with 23 additions and 10 deletions.
  1. +5 −0 src/hiccup/compiler.clj
  2. +6 −5 src/hiccup/core.clj
  3. +12 −5 src/hiccup/util.clj
View
5 src/hiccup/compiler.clj
@@ -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))
@@ -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
View
11 src/hiccup/core.clj
@@ -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)
View
17 src/hiccup/util.clj
@@ -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
@@ -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")

0 comments on commit 07a4097

Please sign in to comment.
Something went wrong with that request. Please try again.