clojure-demos/resources/public/documents/examples-xml-sitemap.org

183 lines
6.5 KiB
Org Mode

#+TITLE: Generating xml to produce a sitemap
* Introduction
In this example we generate a sitemap the example uses reader conditionals so the code works in clojure and clojurescript it also has a simple macro to output the file if used in the frontend.
#+BEGIN_SRC html :results silent :exports none :tangle readme.org
Install dependencies with.
npm install
Run the project with the below command
npx shadow-cljs watch app
Alternatively jack into the project from your ide.
Once launched you should see a sitemap.xml file generated inside this project.
#+END_SRC
#+BEGIN_SRC edn :results silent :exports none :tangle deps.edn
{:paths ["src" "resources"]
:deps
{org.clojure/clojure {:mvn/version "1.10.0"}
org.clojure/clojurescript {:mvn/version "1.11.60"}
org.clojure/data.xml {:mvn/version "0.2.0-alpha8"}
tick/tick {:mvn/version "0.6.2"}
reagent/reagent {:mvn/version "1.2.0"}
thheller/shadow-cljs {:mvn/version "2.24.0"}}}
#+END_SRC
#+BEGIN_SRC edn :results silent :exports none :tangle shadow-cljs.edn
{:deps {:aliases [:dev]}
:dev-http {8080 ["resources/public/" "classpath:public"]}
:source ["src" "../../components"]
:builds {:app {:output-dir "resources/public/cljs-out/"
:asset-path "/cljs-out"
:target :browser
:compiler-options {:infer-externs :auto
:externs ["datascript/externs.js"]
:output-feature-set :es6}
:modules {:main_bundle {:init-fn clojure-demo.core/startup!}}
:devtools {:after-load app.main/reload!}}}}
#+END_SRC
#+BEGIN_SRC json :results silent :exports none :tangle package.json
{
"dependencies": {
"react": "^18.2.0",
"react-dom": "^18.2.0"
},
"devDependencies": {
"shadow-cljs": "^2.23.3",
"webpack": "^5.74.0",
"webpack-cli": "^4.10.0"
}
}
#+END_SRC
#+BEGIN_SRC html :results silent :exports none :tangle resources/public/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Clojure demos</title>
<script src="https://cdn.tailwindcss.com"></script>
</head>
<body>
<div id="app">
App loading here
</div>
<script src="/cljs-out/main_bundle.js" type="application/javascript"></script>
</body>
</html>
#+END_SRC
** Clojure(script) sitemap generation function
This will work in clojure and clojurescript, the code is slightly different to account for missing feature in the clojurescript version.
We can use a macro to generate a sitemap from a client side app on startup, or just use it directly if generating on a server.
#+BEGIN_SRC clojure :exports none :tangle src/clojure_demo/sitemap.cljc
(ns clojure-demo.sitemap
(:require
[clojure.data.xml :as xml]
[tick.core :as tick]))
#+END_SRC
#+BEGIN_SRC clojure :results value :tangle src/clojure_demo/sitemap.cljc
;;#?(:clj (xml/alias-uri 'sitem "http://www.sitemaps.org/schemas/sitemap/0.9"))
(defn pwa-sitemap [domain routes]
#?(:cljs (xml/emit-str
{:tag :urlset
:attrs {#_#_:xmlns "http://www.sitemaps.org/schemas/sitemap/0.9"}
:content
(mapv (fn [r]
{:tag :url
:attrs {}
:content [{:tag :loc :attrs {} :content [(str domain r)]}
{:tag :lastmod :attrs {} :content [(tick/format :iso-zoned-date-time (tick/zoned-date-time))]}]}
) routes)})
:clj (xml/indent-str
{:tag :urlset
:attrs {:xmlns "http://www.sitemaps.org/schemas/sitemap/0.9"}
:content
(mapv (fn [r]
{:tag :url
:attrs {}
:content [{:tag :loc :attrs {} :content [(str domain r)]}
{:tag :lastmod :attrs {} :content [(tick/format :iso-zoned-date-time (tick/zoned-date-time))]}]}
) routes)})))
(defmacro spit-pwa-sitemap
"Generate the sitemap and outut to the provided path"
{:arglists '([body] [options & body]), :style/indent 0}
[path domain urls]
#?(:clj (spit path (pwa-sitemap domain urls))
:cljs nil))
(comment
(pwa-sitemap "https://example.com/" ["/one" "/two"])
(spit-pwa-sitemap "sitemap.xml" "https://example.com/" ["/one" "/two"]))
#+END_SRC
** Clojurescript usage
This is an example of creating the sitemap inside a frontend application, it call the macro which is evaluated at build and outputs the sitemap.xml
When working with data.xml it is very important to set the xml namespace to avoid an alias being appended to your xml, the namespace should be set in the root xml element and via =alias-uri= then make sure all element tag value are called via the namespace.
Also note namespacing is not supported in clojurescript so alias-uri is not available
Look into why :xmlns breaks sci rendering
Adding the k
#+BEGIN_SRC clojurescript :exports none :tangle src/clojure_demo/core.cljs
(ns clojure-demo.core
(:require
[clojure.data.xml :as xml]
["react-dom/client" :refer [createRoot]]
[reagent.core :as reagent]
[clojure-demo.sitemap :refer [pwa-sitemap]])
(:require-macros [clojure-demo.sitemap :refer [spit-pwa-sitemap]]))
#+END_SRC
Because our routes are just data we could add a =:sitemap= key for the handler maps and filter the routes based on the key or even run custom functions to build up the sitemap dynamically when the contest is generated from a database.
You can reuse the code in the cljc file the sitemap function is replicated here as sci does not work with the reader conditionals in the code.
#+BEGIN_SRC clojurescript :results value :tangle src/clojure_demo/core.cljs
;;Should be set in clojure but it is not supported in clojurescript currently
;;(xml/alias-uri 'sitemap "http://www.sitemaps.org/schemas/sitemap/0.9")
(def routes
[["/"
{:name ::frontpage
:view prn}]
["/about"
{:name ::about
:view prn}]
["/item/:id"
{:name ::item
:view prn
:parameters {:path {:id int?}}}]])
;; map first over the routes so we only get strings
(->> routes
(mapv first)
(pwa-sitemap "https://example.com" ))
#+END_SRC
#+BEGIN_SRC clojure :exports none :tangle src/clojure_demo/core.cljs
(defn current-page []
[:pre (str (pwa-sitemap "https://example.com" ["/one" "/two"]))])
(defn mount-root-page []
;; this select the main node from the html file and injects your page content
(.render
(createRoot (.getElementById js/document "app"))
(reagent/as-element [current-page])))
;; call our macro to generate the sitemap file
(spit-pwa-sitemap "sitemap.xml" "https://example.com" ["/one" "/two"])
(def startup! (mount-root-page))
#+END_SRC