Skip to content

Latest commit

 

History

History
117 lines (86 loc) · 3.04 KB

README.md

File metadata and controls

117 lines (86 loc) · 3.04 KB

mustache.clj - Logic-less {{mustache}} templates for Clojure

mustache.clj is a (yet another) implementation of the Mustache template system for Clojure.

By preprocessing template into a tree like data structure, It's quite fast.

Motivation

I initally write it for my part time project: Rssminer

  • Rssminer need to fast with limited MEM and CPU
  • It makes the i18n quite easy
  • Mustache is used both server side and client side

Usage

Quick start

[me.shenfeng/mustache "1.0-SNAPSHOT"]

Template

<!-- test/sample.tpl -->
<h1>{{ title }}</h1>
<p class="desc">{{ desc }}</p>
<ul>
  {{#tags}}
    <li class="tag">{{ tag }}</li>{{/tags}}
  {{# hidden }}
    this will not show, if hidden is false or empty list
  {{/ hidden }}
</ul>

Code

(deftemplate tmpl-fn (slurp "test/sample.tpl"))

(def data {:title "mustache.clj"
           :desc "Logic-less {{mustache}} templates for Clojure"
           :tags [{:tag "Clojure"}
                  {:tag "Mustache"}
                  {:tag "Performance"}]})

(println (tmpl-fn data))

Output

<h1>mustache.clj</h1>
<p class="desc">Logic-less {{mustache}} templates for Clojure</p>
<ul>
    <li class="tag">Clojure</li>
    <li class="tag">Mustache</li>
    <li class="tag">Performance</li>
</ul>

Generate functions from templates folder

templates folder:

templates
├── admin.tpl                => admin
├── login.tpl                => login
├── m
│   ├── landing.tpl          => m-landing
│   ├── p_header.tpl         => m-p-header
│   └── subs.tpl             => m-subs
└── tmpls
    ├── app
    │   ├── feed_content.tpl => tmpls-app-feed-content
(gen-tmpls-from-folder "templates" [".tpl"]) ;  generates the clojure fn

; now you can write something like this
(admin {:key "str" :array [1 2 3 5]})

Generate functions from classpath resources

gen-tmpls-from-resources just like mktmpls-from-folder, except find templates files from classpath

Transform template data before apply it to the template

You can pass a function (optional) to deftemplate, mktmpls-from-folder, mktmpls-from-resouces, allows you to transform the template data

(defn add-gloal-data [data]
  (assoc data
    :dev? (config/dev?)                 ; distingish dev and prod
    :server-host (get-in *current-req* [:header "host"]) ; stg1, test, prod host is different
    ;; other data, like different data based on local => for i18n
    ))

(gen-tmpls-from-folder "templates" [".tpl"] add-gloal-data)

Performance

It runs quit fast. It can render the test/sample.tpl with the above data about 500k times per seconds on my 13 inch Macbook Air.

Limitation

  • Set Delimiter is not implemented now. Anyway, why change {{}} to <% %>

License

Distributed under the Eclipse Public License, the same as Clojure.