Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save escherize/6db7224b14e84c845755666cafc9fd74 to your computer and use it in GitHub Desktop.
Save escherize/6db7224b14e84c845755666cafc9fd74 to your computer and use it in GitHub Desktop.
(ns escherize.kenning
(:require [selmer.parser :as parser]))
(defmacro ^:private env-map []
`(apply zipmap [(mapv keyword (quote ~(keys &env))) (vector ~@(keys &env))]))
(defn ^:private resolve-kw [env kw]
(when-let [found-sym (or
(get env kw nil)
(try (eval (symbol kw))
(catch java.lang.RuntimeException _ nil)))]
{kw found-sym}))
(defmacro <<
"Resolves the variables from your template string from the local-env, or the
namespace and puts them into your template for you.
e.g. (let [a 1] (<< \"{{a}} + {{a}} = 2\")) ;;=> \"1 + 1 = 2\" "
[s]
`(->> (parser/known-variables ~s)
(mapv #(resolve-kw (env-map) %))
(apply merge)
(parser/render ~s)))
(comment
(def user "henry")
(<< "Oh, {{user}}!")
;;=> "Oh, henry!"
(let [user "john"]
(<< "{{user}}ny appleseed"))
;;=> "johnny appleseed"
(<< "{{user}}")
;; <= converts to =>
(parser/render "{{user}}" {:user user})
;; <= converts to =>
(parser/render "{{user}}"
(->> "{{user}}"
parser/known-variables
(mapv #(resolve-kw (env-map) %))
(apply merge))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment