Selecting nonexistent elements for the purposes of creating them

29 views
Skip to first unread message

Jonathan Jacobs

unread,
Nov 26, 2015, 7:36:01 AM11/26/15
to Enlive
Hello,

I'm trying to insert a <link> element into <head>, creating <head> if it doesn't exist. I thought (but) might help me but I can't quite figure out how to write this selector.

What I came up with is quite difficult to read and possibly produces poor results given multiple <head> tags or such.

(defn insert-stylesheet-links
  [doc uris]
  (let [no-head? (empty? (html/select doc [:head]))]
    (html/at doc
             [html/root :> (html/pred (constantly no-head?))] (html/append {:tag :head})
             [:head] (html/append (map stylesheet-link uris)))))

Any some insight on how to improve it would be appreciated.

--
Jonathan

Linus Ericsson

unread,
Nov 26, 2015, 9:56:43 AM11/26/15
to enliv...@googlegroups.com
A non-existing tag is not transformed in Enlive. This is quite clever since it decouples the design from the transforms, a designer can add or remove tags to control what is shown.

In your case you want to make sure that a head is added if it doesn't exist already, which get's a bit strange of the reasons you mention. It would be much easier if there was guarantees of a place-holder in the template.

Could something like having a meta-template with a (default) header and body make sense? Then you could use #'substitute to replace the head-tag if the template you want to render have a head-tag.

If you want to use code like the one you already have, I would make the transform in two steps, first make looking for a head-tag and if it didn't exist, I would add it.

In the next step I would add CSS-links in the header, which is now guaranteed to exist.

/Linus

--
You received this message because you are subscribed to the Google Groups "Enlive" group.
To unsubscribe from this group and stop receiving emails from it, send an email to enlive-clj+...@googlegroups.com.
To post to this group, send email to enliv...@googlegroups.com.
Visit this group at http://groups.google.com/group/enlive-clj.
For more options, visit https://groups.google.com/d/optout.

Reply all
Reply to author
Forward
0 new messages