From 451e3c739e1ba7a7c9adecbee35b11e88097fedf Mon Sep 17 00:00:00 2001 From: gered Date: Sat, 1 Mar 2014 14:25:01 -0500 Subject: [PATCH] add support for rendering templates from files --- src/clj_jtwig/core.clj | 41 +++++++++++++++++++++++++++++++++-------- 1 file changed, 33 insertions(+), 8 deletions(-) diff --git a/src/clj_jtwig/core.clj b/src/clj_jtwig/core.clj index d1d8cb7..14c8179 100644 --- a/src/clj_jtwig/core.clj +++ b/src/clj_jtwig/core.clj @@ -1,15 +1,40 @@ (ns clj-jtwig.core - (:require [clojure.walk :refer [stringify-keys]]) - (:import (com.lyncode.jtwig JtwigTemplate JtwigContext))) + (:require [clojure.walk :refer [stringify-keys]] + [clojure.java.io :as io]) + (:import (com.lyncode.jtwig JtwigTemplate JtwigContext) + (java.io File))) -(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 & {:keys [skip-model-map-stringify?] :as options}] - (let [template (new JtwigTemplate s) - context (new JtwigContext)] +(defn- get-resource-path [filename] + (-> (Thread/currentThread) + (.getContextClassLoader) + (.getResource filename))) + +(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? (stringify-keys model-map) model-map)] (.set context k v)) (.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)))