Search code examples
clojureselmer

Iterate over a map in selmer


I would like to iterate over a map in selmer, in such a way that allows my to print the keys as well as the values. As far as I can see this is not supported out of the box, so I have tried the following:

(defn mapper-tag [args context-map content]
  (when-let [map-data (get context-map (keyword (first args))
                           (get context-map (first args)))]
    (apply str (for [[k v] map-data]
                 (selmer.parser/render (get-in content [:mapper :content]) {:key k :val v})))))

(selmer.parser/add-tag! :mapper mapper-tag :endmapper)
(selmer.parser/render  "{% mapper m %}KEY {{key}} \n{% endmapper %}"  {:m  {:a 1 :b 1}})

I expect this to output something like KEY a KEY b

But it outputs

KEY KEY

Any pointers?


Solution

  • Maps in Clojure are seqs so you can just use selmer for:

     (selmer.filters/add-filter! :key key)
     (selmer.filters/add-filter! :val val)
     (selmer.parser/render  "{% for item in m %} KEY is {{item|key}} VALUES is {{item|val}}\n{% endfor %}"  {:m  {:a 1 :b 1}})