Writing web applications in Clojure
Templating
The project.clj
file defines two other dependencies: Hiccup [11] and Enlive [12]. Both are templating libraries, but each takes a different approach.
Listing 3 makes Hiccup available, and app
has now changed: The application no longer uses the "Hello, World!" string, but calls the root
function, which is defined in the line above. It uses Hiccup to output HTML. An interesting feature of Clojure is that the developer can modify parts of the code without touching the rest of the virtual machine. Because the task of creating HTML code is outsourced to a separate function, the developer can change it and immediately see the effect on the application.
Listing 3
src/webapp/core.clj
Good Day!
You could change the greeting to "Good day," for example. If the REPL is already in the webapp.core
namespace, the defined aliases are available:
webapp.core=> (hiccup/html [:h1 [:em "Good Day"] ", Hiccup!"]) "<h1>Good Day,, Hiccup!</h1>"
The return value looks good – the following code stores the change in src/webapp/core.clj
:
(defn root [] (hiccup/html [:h1 [:em "Good Day"] ",Hiccup!"]))
The next input reloads the namespace after saving the file:
webapp.core=> (require 'webapp.core :reload) nil
The developer does not need to restart the server. The new behavior of the root
function should be visible after reloading the page in the browser.
Hiccup uses a typical Clojure-style approach to generating HTML, by mapping the data into simple structures. Because common types such as lists, vectors, maps, and sets have a common programming interface, Hiccup templates can be conveniently processed with the usual Clojure functions.
If you work with web designers who are used to working with HTML, Hiccup is not much fun. For this scenario, you will probably want to use the Enlive templating library instead. A simple template, stored as a file in resources/templates/index.html
, is shown in Listing 4.
Listing 4
resources/templates/index.html
The new version of src/webapp/core.clj
in Listing 5 uses :require
to include the Enlive library. The deftemplate
function replaces the previous definition of root
and applies the template. It takes no arguments and simply pushes Hello, Enlive!
into the <h1>
HTML element of the template. To make the change effective, simply reload the namespace in REPL and the page in the browser.
Listing 5
src/webapp/core.clj
If you would like, you can continue these experiments with REPL on your own. To do so, change a little something – maybe break something – and fix it again. Refer to the useful REPL documentation and source code for information on functions. The clojure.repl/doc
and clojure.repl/source
commands are used for this, as the sample session in Listing 6 shows.
Listing 6
Documentation and Source Code
A Chat Application
Now that you've taken your first steps with Clojure, I'll move on to a webchat app that uses WebSockets. The sample application consists of only four files. project.clj
(Listing 7) contains the known list of dependencies: Clojure itself and three libraries. However, the :main
key makes the following webapp.main
the main namespace of the application.
Listing 7
project.clj
The nested map next to :profiles
stipulates that Leiningen should compile all namespaces to create Java class files :aot
(ahead of time) before executing. These two settings make it possible to export the application as a JAR archive later on.
The webapp.core
namespace, as shown in Listing 8, has changed substantially, however. Among the required namespaces (:require
) you will now also find the wrap-params
function from ring.middleware.params
. With its help, the application can access parameters from HTTP requests in the form of a hash.
Listing 8
src/webapp/core.clj
Even the root
template in line 7 is different. It now takes request
as its only argument. If the template is invoked, it searches the HTML object tree for the CSS selector #name
. After finding this, it sets the appropriate value from the request
hash, which has the following structure:
{:params {"name" "<sought after value>"}}
From line 37 onward, the listing defines the app
function. This first creates an atom (a container that stores other objects) that comprises an empty set and is bound to the symbol channels
. This atom will store references to all connections to the chat room and can only be changed by atomic transactions. Thus, a change is either completed, or Clojure retries.
« Previous 1 2 3 Next »
Buy this article as PDF
(incl. VAT)
Buy Linux Magazine
Subscribe to our Linux Newsletters
Find Linux and Open Source Jobs
Subscribe to our ADMIN Newsletters
Support Our Work
Linux Magazine content is made possible with support from readers like you. Please consider contributing when you’ve found an article to be beneficial.
News
-
The Gnome Foundation Struggling to Stay Afloat
The foundation behind the Gnome desktop environment is having to go through some serious belt-tightening due to continued financial problems.
-
Thousands of Linux Servers Infected with Stealth Malware Since 2021
Perfctl is capable of remaining undetected, which makes it dangerous and hard to mitigate.
-
Halcyon Creates Anti-Ransomware Protection for Linux
As more Linux systems are targeted by ransomware, Halcyon is stepping up its protection.
-
Valve and Arch Linux Announce Collaboration
Valve and Arch have come together for two projects that will have a serious impact on the Linux distribution.
-
Hacker Successfully Runs Linux on a CPU from the Early ‘70s
From the office of "Look what I can do," Dmitry Grinberg was able to get Linux running on a processor that was created in 1971.
-
OSI and LPI Form Strategic Alliance
With a goal of strengthening Linux and open source communities, this new alliance aims to nurture the growth of more highly skilled professionals.
-
Fedora 41 Beta Available with Some Interesting Additions
If you're a Fedora fan, you'll be excited to hear the beta version of the latest release is now available for testing and includes plenty of updates.
-
AlmaLinux Unveils New Hardware Certification Process
The AlmaLinux Hardware Certification Program run by the Certification Special Interest Group (SIG) aims to ensure seamless compatibility between AlmaLinux and a wide range of hardware configurations.
-
Wind River Introduces eLxr Pro Linux Solution
eLxr Pro offers an end-to-end Linux solution backed by expert commercial support.
-
Juno Tab 3 Launches with Ubuntu 24.04
Anyone looking for a full-blown Linux tablet need look no further. Juno has released the Tab 3.