Search code examples
clojureenlive

Enlive Predefined selector-steps


I'm trying to use Enlive to clone the replace-me script tag in this html.

<!DOCTYPE html>
<html lang="en">
  <head>
[...]
    <script src="/js/libs/less.min.js"></script>
    <script src="replace-me"></script>
  </head>
[...]

Question 1)

I'm struggling to figure out what the "idiomatic" selector for the last script element is. Currently I'm using

(h/select tpl [:head :> [h/last-of-type :script]])

is that correct?

Question 2)

I have this snippet to transform the entire head entity:

(h/defsnippet head "templates/base.html" [:head]
  [{:keys [scripts]}]
  [h/root :> [h/last-of-type :script]]
  (h/clone-for [script scripts]
               (h/set-attr :src (:src script))))

Is this the correct usage of the root selector-step? I'm assuming that within the context of defsnippet, root is referencing the [:head] selector, is that correct?

Thanks!


Solution

    1. This works in this case, but you might prefer attr-has:

      (h/select tpl [[:script (h/attr-has :src "replace-me")]])
      
      (h/defsnippet head "templates/base.html" [:head]
        [{:keys [scripts]}]
        [h/root :> (h/attr-has :src "replace-me")]
        (h/clone-for [script scripts]
                     (h/set-attr :src (:src script))))
      

      In more complex cases you could define your own selectors. Here it's unnecessary because of attr-has, but for the sake of example:

      (def my-pred (h/pred #(= #{"replace.me"} (h/attr-values % :src))))
      
      (h/defsnippet head "templates/base.html" [:head]
        [{:keys [scripts]}]
        [h/root :> my-pred]
        (clone-for [script scripts]
                   (h/set-attr :src (:src script))))
      
    2. You can use emit* to check whether your snippets produce the desired results:

      (apply println (h/emit* (head {:scripts [{:src "bar.js"}]})))