3

我想在 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

任何指针?

4

2 回答 2

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}})
于 2016-01-28T23:21:22.720 回答
2

Selmer's built-in {% for %} loop allows for destructuring, so you can pull out the key/value right there in the template:

(selmer.parser/render
  "{% for key,val in m %}KEY: {{key}}, VALUE: {{val}}\n{% endfor %}"
  {:m {:a 1 :b 1}})

Output:

KEY: a, VALUE: 1
KEY: b, VALUE: 1
于 2020-07-02T04:54:08.873 回答