add support for template function aliases

This commit is contained in:
Gered 2014-03-04 12:10:43 -05:00
parent f879a59b72
commit bd6b5962cb

View file

@ -25,25 +25,41 @@
(catch FunctionNotFoundException ex (catch FunctionNotFoundException ex
false))) false)))
(defn- make-aliases-array [aliases]
(let [n (count aliases)
array (make-array String n)]
(doseq [index (range n)]
(aset array index (nth aliases index)))
array))
(defn add-function! (defn add-function!
"adds a new template function using the name specified. templates can call the function by the "adds a new template function using the name specified. templates can call the function by the
name specified and passing in the same number of arguments accepted by f. the return value of name specified (or one of the aliases specified) and passing in the same number of arguments
f is returned to the template. accepted by f. the return value of f is returned to the template. if this function has no aliases
then nil can be specified for the aliases arg.
prefer to use the 'deftwigfn' macro when possible." prefer to use the 'deftwigfn' macro when possible."
[name f] [name aliases f]
(let [handler (reify JtwigFunction (let [handler (reify JtwigFunction
(execute [_ arguments] (execute [_ arguments]
(try (try
(clojure->java (apply f (map java->clojure arguments))) (clojure->java (apply f (map java->clojure arguments)))
(catch Exception ex (catch Exception ex
(throw (new FunctionException ex))))))] (throw (new FunctionException ex))))))]
(.add @functions handler name (make-array String 0)) (.add @functions handler name (make-aliases-array aliases))
(.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
same number of arguments as in args. the return value of the last form in body is returned to the same number of arguments as in args. the return value of the last form in body is returned to the
template." template. functions defined this way have no aliases and can only be called by the name given."
[fn-name args & body] [fn-name args & body]
`(do `(do
(add-function! ~fn-name (fn ~args ~@body)))) (add-function! ~fn-name nil (fn ~args ~@body))))
(defmacro defaliasedtwigfn
"adds a new template function. templates can call it by by the name specified (or one of the
aliases specified) and passing in the same number of arguments as in args. the return value of
the last form in body is returned to the template."
[fn-name args aliases & body]
`(do
(add-function! ~fn-name ~aliases (fn ~args ~@body))))