我想在selmer中迭代一个地图,这样我就可以打印键和值。据我所知,开箱即用不支持,所以我尝试了以下内容:
(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}})
我希望这能输出类似的东西
KEY a
KEY b
但它输出
KEY
KEY
任何指针?
答案 0 :(得分:2)
Clojure中的地图是seqs,所以你可以使用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}})
答案 1 :(得分:1)
Selmer的内置{% for %}
循环allows for destructuring,因此您可以在模板中直接提取键/值:
(selmer.parser/render
"{% for key,val in m %}KEY: {{key}}, VALUE: {{val}}\n{% endfor %}"
{:m {:a 1 :b 1}})
输出:
KEY: a, VALUE: 1
KEY: b, VALUE: 1