• Stars
    star
    773
  • Rank 58,789 (Top 2 %)
  • Language
    Clojure
  • Created over 12 years ago
  • Updated almost 4 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A client-side router for ClojureScript.

secretary

A client-side router for ClojureScript.

Clojars Project cljdoc badge CircleCI

Contents

Installation

Add secretary to your project.clj :dependencies vector:

[clj-commons/secretary "1.2.4"]

For the current SNAPSHOT version use:

[clj-commons/secretary "1.2.5-SNAPSHOT"]

Guide

To get started :require secretary somewhere in your project.

(ns app.routes
  (:require [secretary.core :as secretary :refer-macros [defroute]]))

Note: starting ClojureScript v0.0-2371, :refer cannot be used to import macros into your project anymore. The proper way to do it is by using :refer-macros as above. When using ClojureScript v0.0-2755 or above, if (:require [secretary.core :as secretary]) is used, macros will be automatically aliased to secretary, e.g. secretary/defroute.

Basic routing and dispatch

Secretary is built around two main goals: creating route matchers and dispatching actions. Route matchers match and extract parameters from URI fragments and actions are functions which accept those parameters.

defroute is Secretary's primary macro for defining a link between a route matcher and an action. The signature of this macro is [name? route destruct & body]. We will skip the name? part of the signature for now and return to it when we discuss named routes. To get clearer picture of this let's define a route for users with an id.

(defroute "/users/:id" {:as params}
  (js/console.log (str "User: " (:id params))))

In this example "/users/:id" is route, the route matcher, {:as params} is destruct, the destructured parameters extracted from the route matcher result, and the remaining (js/console.log ...) portion is body, the route action.

Before going in to more detail let's try to dispatch our route.

(secretary/dispatch! "/users/gf3")

With any luck, when we refresh the page and view the console we should see that User: gf3 has been logged somewhere.

Route matchers

By default the route matcher may either be a string or regular expression. String route matchers have special syntax which may be familiar to you if you've worked with Sinatra or Ruby on Rails. When secretary/dispatch! is called with a URI it attempts to find a route match and it's corresponding action. If the match is successful, parameters will be extracted from the URI. For string route matchers these will be contained in a map; for regular expressions a vector.

In the example above, the route matcher "/users/:id" successfully matched against "/users/gf3" and extracted {:id "gf3} as parameters. You can refer to the table below for more examples of route matchers and the parameters they return when matched successfully.

Route matcher URI Parameters
"/:x/:y" "/foo/bar" {:x "foo" :y "bar"}
"/:x/:x" "/foo/bar" {:x ["foo" "bar"]}
"/files/*.:format" "/files/x.zip" {:* "x" :format "zip"}
"*" "/any/thing" {:* "/any/thing"}
"/*/*" "/n/e/thing" {:* ["n" "e/thing"]}
"/*x/*y" "/n/e/thing" {:x "n" :y "e/thing"}
#"/[a-z]+/\d+" "/foo/123" ["/foo/123"]
#"/([a-z]+)/(\d+)" "/foo/123" ["foo" "123"]

Parameter destructuring

Now that we understand what happens during dispatch we can look at the destruct argument of defroute. This part is literally sugar around let. Basically whenever one of our route matches is successful and extracts parameters this is where we destructure them. Under the hood, for example with our users route, this looks something like the following.

(let [{:as params} {:id "gf3"}]
  ...)

Given this, it should be fairly easy to see that we could have have written

(defroute "/users/:id" {id :id}
  (js/console.log (str "User: " id)))

and seen the same result. With string route matchers we can go even further and write

(defroute "/users/:id" [id]
  (js/console.log (str "User: " id)))

which is essentially the same as saying {:keys [id]}.

For regular expression route matchers we can only use vectors for destructuring since they only ever return vectors.

(defroute #"/users/(\d+)" [id]
  (js/console.log (str "User: " id)))

Query parameters

If a URI contains a query string it will automatically be extracted to :query-params for string route matchers and to the last element for regular expression matchers.

(defroute "/users/:id" [id query-params]
  (js/console.log (str "User: " id))
  (js/console.log (pr-str query-params)))

(defroute #"/users/(\d+)" [id {:keys [query-params]}]
  (js/console.log (str "User: " id))
  (js/console.log (pr-str query-params)))

;; In both instances...
(secretary/dispatch! "/users/10?action=delete")
;; ... will log
;; User: 10
;; "{:action \"delete\"}"

Named routes

While route matching and dispatch is by itself useful, it is often necessary to have functions which take a map of parameters and return a URI. By passing an optional name to defroute Secretary will define this function for you.

(defroute users-path "/users" []
  (js/console.log "Users path"))

(defroute user-path "/users/:id" [id]
  (js/console.log (str "User " id "'s path"))

(users-path) ;; => "/users"
(user-path {:id 1}) ;; => "/users/1"

This also works with :query-params.

(user-path {:id 1 :query-params {:action "delete"}})
;; => "/users/1?action=delete"

If the browser you're targeting does not support HTML5 history you can call

(secretary/set-config! :prefix "#")

to prefix generated URIs with a "#".

(user-path {:id 1})
;; => "#/users/1"
This scheme doesn't comply with URI spec

Beware that using :prefix that way will make resulting URIs no longer compliant with standard URI syntax โ€“ the fragment must be the last part of the URI after the query). Indeed, the syntax of a URI is defined as:

scheme:[//[user:password@]host[:port]][/]path[?query][#fragment]

secretary adds a # after the path so it makes the fragment hide the query. For instance, the following URL is comprehended in different ways by secretary and the spec:

https://www.example.com/path/of/app#path/inside/app?query=params&as=defined&by=secretary
  • the fragment is "path/inside/app?query=params&as=defined&by=secretary" for standard libraries, but is "path/inside/app" according to Secretary

  • the query is "" for standard libraries, but is "query=params&as=defined&by=secretary" according to Secretary

Available protocols

You can extend Secretary's protocols to your own data types and records if you need special functionality.

IRenderRoute

Most of the time the defaults will be good enough but on occasion you may need custom route rendering. To do this implement IRenderRoute for your type or record.

(defrecord User [id]
  secretary/IRenderRoute
  (render-route [_]
    (str "/users/" id))

  (render-route [this params]
    (str (secretary/render-route this) "?"
         (secretary/encode-query-params params))))

(secretary/render-route (User. 1))
;; => "/users/1"
(secretary/render-route (User. 1) {:action :delete})
;; => "/users/1?action=delete"

IRouteMatches

It is seldom you will ever need to create your own route matching implementation as the built in String and RegExp routes matchers should be fine for most applications. Still, if you have a suitable use case then this protocol is available. If your intention is to is to use it with defroute your implementation must return a map or vector.

Example with goog.History

(ns example
  (:require [secretary.core :as secretary :refer-macros [defroute]]
            [goog.events :as events])
  (:import [goog History]
           [goog.history EventType]))

(def application
  (js/document.getElementById "application"))

(defn set-html! [el content]
  (aset el "innerHTML" content))

(secretary/set-config! :prefix "#")

;; /#/
(defroute home-path "/" []
  (set-html! application "<h1>OMG! YOU'RE HOME!</h1>"))

;; /#/users
(defroute users-path "/users" []
  (set-html! application "<h1>USERS!</h1>"))

;; /#/users/:id
(defroute user-path "/users/:id" [id]
  (let [message (str "<h1>HELLO USER <small>" id "</small>!</h1>")]
    (set-html! application message)))

;; /#/777
(defroute jackpot-path "/777" []
  (set-html! application "<h1>YOU HIT THE JACKPOT!</h1>"))

;; Catch all
(defroute "*" []
  (set-html! application "<h1>LOL! YOU LOST!</h1>"))

;; Quick and dirty history configuration.
(doto (History.)
  (events/listen EventType.NAVIGATE #(secretary/dispatch! (.-token %)))
  (.setEnabled true))

Contributors

Committers

License

Distributed under the Eclipse Public License, the same as Clojure.

More Repositories

1

aleph

Asynchronous streaming communication for Clojure - web server, web client, and raw TCP/UDP
Clojure
2,544
star
2

kibit

There's a function for that!
Clojure
1,765
star
3

seesaw

Seesaw turns the Horror of Swing into a friendly, well-documented, Clojure library
Clojure
1,445
star
4

manifold

A compatibility layer for event-driven abstractions
Clojure
1,017
star
5

etaoin

Pure Clojure Webdriver protocol implementation
Clojure
913
star
6

marginalia

Ultra-lightweight literate programming for clojure inspired by docco
Clojure
816
star
7

hickory

HTML as data
Clojure
634
star
8

claypoole

Claypoole: Threadpool tools for Clojure
Clojure
607
star
9

pretty

Library for helping print things prettily, in Clojure - ANSI fonts, formatted exceptions
Clojure
597
star
10

rewrite-clj

Rewrite Clojure code and edn
Clojure
576
star
11

potemkin

some ideas which are almost good
Clojure
568
star
12

pomegranate

A sane Clojure API for Maven Artifact Resolver + dynamic runtime modification of the classpath
Clojure
504
star
13

gloss

speaks in bytes, so you don't have to
Clojure
483
star
14

camel-snake-kebab

A Clojure[Script] library for word case conversions
Clojure
476
star
15

cljss

Clojure Style Sheets โ€” CSS-in-JS for ClojureScript
Clojure
455
star
16

clooj

clooj, a lightweight IDE for clojure
Clojure
421
star
17

byte-streams

A Rosetta stone for JVM byte representations
Clojure
417
star
18

durable-queue

a disk-backed queue for clojure
Clojure
381
star
19

useful

Some Clojure functions we use all the time, and so can you.
Clojure
365
star
20

metrics-clojure

A thin faรงade around Coda Hale's metrics library.
Clojure
343
star
21

virgil

Recompile Java code without restarting the REPL
Clojure
302
star
22

citrus

State management library for Rum
Clojure
274
star
23

ordered

Ordered sets and maps, implemented in pure clojure
Clojure
253
star
24

clj-ssh

SSH commands via jsch
Clojure
227
star
25

dirigiste

centrally-planned object and thread pools
Java
204
star
26

iapetos

A Clojure Prometheus Client
Clojure
176
star
27

primitive-math

for the discerning arithmetician
Clojure
170
star
28

humanize

Produce human readable strings in clojure
Clojure
156
star
29

digest

Digest algorithms (md5, sha1 ...) for Clojure
Clojure
156
star
30

clj-yaml

YAML encoding and decoding for Clojure
Clojure
120
star
31

byte-transforms

methods for hashing, compressing, and encoding bytes
Clojure
104
star
32

ring-buffer

A persistent ring-buffer in Clojure
Clojure
96
star
33

tentacles

An Octocat is nothing without his tentacles
Clojure
80
star
34

fs

File system utilities for Clojure. (forked from Raynes/fs)
Clojure
72
star
35

lein-marginalia

A Marginalia plugin to Leiningen
HTML
69
star
36

meta

A meta-repo for clj-commons discussions
46
star
37

ring-gzip-middleware

GZIP your Ring responses
Clojure
41
star
38

rewrite-cljs

Traverse and rewrite Clojure/ClojureScript/EDN from ClojureScript
Clojure
41
star
39

formatter

Building blocks and discussion for building a common Clojure code formatter
36
star
40

vizdeps

Visualize Leiningen dependencies using Graphviz
Clojure
33
star
41

zprint-clj

Node.js wrapper for ZPrint Clojure source code formatter
Clojure
13
star
42

infra

Infrastructure for clj-commons
Clojure
2
star
43

clj-commons.github.io

Clojure Commons Site
HTML
1
star