allow redefining template functions. wrap exceptions in FunctionException

This commit is contained in:
Gered 2014-03-04 10:53:23 -05:00
parent 6128447121
commit 1e46b1f207

View file

@ -3,7 +3,7 @@
functions added by default in all jtwig function repository objects" functions added by default in all jtwig function repository objects"
(:import (com.lyncode.jtwig.functions JtwigFunction) (:import (com.lyncode.jtwig.functions JtwigFunction)
(com.lyncode.jtwig.functions.repository DefaultFunctionRepository) (com.lyncode.jtwig.functions.repository DefaultFunctionRepository)
(com.lyncode.jtwig.functions.exceptions FunctionNotFoundException)) (com.lyncode.jtwig.functions.exceptions FunctionNotFoundException FunctionException))
(:require [clj-jtwig.convert :refer [java->clojure clojure->java]])) (:require [clj-jtwig.convert :refer [java->clojure clojure->java]]))
(defn- create-function-repository [] (defn- create-function-repository []
@ -31,13 +31,15 @@
f is returned to the template. f is returned to the template.
prefer to use the 'deftwigfn' macro when possible." prefer to use the 'deftwigfn' macro when possible."
[name f] [name f]
(if (function-exists? name)
(throw (new Exception (str "JTwig template function \"" name "\" already defined.")))
(let [handler (reify JtwigFunction (let [handler (reify JtwigFunction
(execute [_ arguments] (execute [_ arguments]
(clojure->java (apply f (map java->clojure arguments)))))] (try
(clojure->java (apply f (map java->clojure arguments)))
(catch Exception ex
(println "exception!")
(throw (new FunctionException (.getMessage ex) ex))))))]
(.add @functions handler name (make-array String 0)) (.add @functions handler name (make-array String 0))
(.retrieve @functions name)))) (.retrieve @functions name)))
(defmacro deftwigfn (defmacro deftwigfn
"adds a new template function. templates can call it by by the name specified and passing in the "adds a new template function. templates can call it by by the name specified and passing in the