weavejester / hiccup

Fast library for rendering HTML in Clojure
http://weavejester.github.io/hiccup
Eclipse Public License 1.0
2.68k stars 175 forks source link

Fragment equivalent for the back end. #193

Closed sirmspencer closed 2 years ago

sirmspencer commented 2 years ago

Returning multiple tags from a when statement isnt possible (only the last is returned). On the front end, at least with reagent, we would use a fragment to wrap the two tags. On the backend there is no equivalent.

This does not work

(when-let [ga-id (get-config :ga-id)]
     [:script {:async true :src (str "https://www.googletagmanager.com/gtag/js?id=" ga-id)}]
     [:script (str "window.dataLayer = window.dataLayer || [];")])

This would be how we do it on the front end

(when-let [ga-id (get-config :ga-id)]
     [:<> 
      [:script {:async true :src (str "https://www.googletagmanager.com/gtag/js?id=" ga-id)}]
      [:script (str "window.dataLayer = window.dataLayer || [];")]])

A back end equivalent would be great.

Im looking through the code and it looks like (compile-element :default) should be able to expand the following:

(when-let [ga-id (get-config :ga-id)]
     [
      [:script {:async true :src (str "https://www.googletagmanager.com/gtag/js?id=" ga-id)}]
      [:script (str "window.dataLayer = window.dataLayer || [];")]])

But I am still getting and error [:script {:async true, :src \"https:\/\/www.googletagmanager.com\/gtag\/js?id=G-B86B6YVNL5\"}] is not a valid element name." (normalize-element*).

weavejester commented 2 years ago

Returning multiple tags from a when statement isnt possible (only the last is returned).

It is: return a list.

(when-let [ga-id (get-config :ga-id)]
  (list
   [:script {:async true :src (str "https://www.googletagmanager.com/gtag/js?id=" ga-id)}]
   [:script (str "window.dataLayer = window.dataLayer || [];")]))

I believe this syntax works in Reagent as well.

sirmspencer commented 2 years ago

Returning multiple tags from a when statement isnt possible (only the last is returned).

It is: return a list.

(when-let [ga-id (get-config :ga-id)]
  (list
   [:script {:async true :src (str "https://www.googletagmanager.com/gtag/js?id=" ga-id)}]
   [:script (str "window.dataLayer = window.dataLayer || [];")]))

I believe this syntax works in Reagent as well.

Awesome, thanks! I didnt think to try (list ), only [ ] and '( ).