add support for rendering templates from files

This commit is contained in:
Gered 2014-03-01 14:25:01 -05:00
parent d24ecdca24
commit 451e3c739e

View file

@ -1,15 +1,40 @@
(ns clj-jtwig.core (ns clj-jtwig.core
(:require [clojure.walk :refer [stringify-keys]]) (:require [clojure.walk :refer [stringify-keys]]
(:import (com.lyncode.jtwig JtwigTemplate JtwigContext))) [clojure.java.io :as io])
(:import (com.lyncode.jtwig JtwigTemplate JtwigContext)
(java.io File)))
(defn render (defn- get-resource-path [filename]
"renders a template contained in the provided string, using the values in model-map (-> (Thread/currentThread)
as the model for the template." (.getContextClassLoader)
[s model-map & {:keys [skip-model-map-stringify?] :as options}] (.getResource filename)))
(let [template (new JtwigTemplate s)
context (new JtwigContext)] (defn- render-template
[template model-map & [{:keys [skip-model-map-stringify?] :as options}]]
(let [context (new JtwigContext)]
(doseq [[k v] (if-not skip-model-map-stringify? (doseq [[k v] (if-not skip-model-map-stringify?
(stringify-keys model-map) (stringify-keys model-map)
model-map)] model-map)]
(.set context k v)) (.set context k v))
(.output template context))) (.output template context)))
(defn render
"renders a template contained in the provided string, using the values in model-map
as the model for the template."
[s model-map & [options]]
(let [template (new JtwigTemplate s)]
(render-template template model-map options)))
(defn render-file
"renders a template from a file, using the values in model-map as the model for the template"
[filename model-map & [options]]
(let [file (new File filename)
template (new JtwigTemplate file)]
(render-template template model-map options)))
(defn render-resource
"renders a template from a resource file, using the values in the model-map as the model for
the template."
[filename model-map & [options]]
(if-let [resource-filename (get-resource-path filename)]
(render-file (.getPath resource-filename) model-map options)))