Created
January 4, 2014 13:16
-
-
Save knjname/8255237 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| (def var-pattern #"\$\{(.+?)\}") | |
| (def section-pattern #"@\{(\w+)(.*?)\}") | |
| (def section-tokens #"\S+") | |
| (def template-section-definitions (atom {})) | |
| (defn get-template-generator [name] | |
| (get @template-section-definitions name)) | |
| (defn def-template-section [section-name body-generator] | |
| (swap! template-section-definitions | |
| merge {section-name body-generator})) | |
| (def-template-section "if" | |
| (fn [body] | |
| `(if true ~@body))) | |
| (def-template-section "for" | |
| (fn [body] | |
| `(for [bound-var seq] | |
| ~@body))) | |
| (defn compile-leaf-fn [str] | |
| str) | |
| (defn compile-section-fn | |
| ([template expressions] | |
| (let [m (re-matcher section-pattern template)] | |
| (if (.find m) | |
| (let [string-part (.substring template 0 (.start m)) | |
| child-template (.substring template (.end m)) | |
| section-name (.group m 1)] | |
| (if (= "end" section-name) | |
| [child-template (concat expressions [string-part])] | |
| (let [[rest-template exp] (compile-section-fn child-template []) | |
| expr-gen (get-template-generator section-name) | |
| child-expr (expr-gen exp)] | |
| (recur rest-template (concat expressions [string-part] [child-expr]))))) | |
| ["" (concat expressions [template])])))) | |
| (println (second | |
| (compile-section-fn | |
| " | |
| @{for} | |
| foo | |
| @{if} bar | |
| @{for} baz @{end} | |
| hoge | |
| @{end} | |
| fuga | |
| @{if} | |
| piyo | |
| @{end} | |
| boo | |
| @{end}" []))) | |
| (println (second (compile-section-fn | |
| "asdf" []))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment