How to generate a list of a pair of elements in Enlive?

130 views Asked by At

I'm new to Enlive. I found that I can iterate with clone-for, however, it works for single element. I want to generate a list of a pair of elements like the following:

<div>
  <a href="url1">item 1</a><br>
  <a href="url2">item 2</a><br>
  ...
</div>

I tried to select <a> and use clone-for, but end with following result:

<div>
  <a href="url1">item 1</a><a href="url2">item 2</a>......<br>
</div>

What do I do to repeat <a> with <br> in each iteration?

1

There are 1 answers

2
Daniel Neal On BEST ANSWER

I think fragments will work in this case.

Try something along these lines:

(html/sniptest "<div><a href=\"url\">Label</a><br/></div>" {[:a] [:br]} 
  (clone-for [{label :label url :url} [{:label "Google" :url "http://www.google.com" }
                                       {:label "Stack Overflow" :url "http://www.stackoverflow.com"}]]
             [:a] (do-> (content label)
                        (set-attr :href url)))))
;; =>
<div>
     <a href="http://www.google.com">Google</a><br />
     <a href="http://www.stackoverflow.com">Stack Overflow</a><br />
</div>

If you always want the full content of the div to be cloned (not just the fragment :a -> :br) then you can use first-child and last-child. Just change the {[:a] [:br]} selector above to {[:div first-child] [:div last-child]}.