There is this very handy function in Clojure, which is called format
.
It's known for it's ability to easily template strings. The function is commonly available in most of the programming languages.
I was a bit irritated to discover that ClojureScript does not implement this function. As far as I could research it was implemented in older versions but the latest one doesn't contain the function.
Anyone knows if there is a reason for this?
format
exists in ClojureScript. It comes from the Google Closure Library (GCL), which is a fundamental part of ClojureScript. Unfortunately it can be tricky to use it. The conventional way is to require both [goog.string :as gstring]
and [goog.string.format]
, and then to use gstring.format
. For example:
(ns rostering.components.services
(:require
[goog.string :as gstring]
[goog.string.format]))
(str "$" (gstring/format "%.2f" 2.5))
Pretty much the same example is at the bottom of this short page of documentation.
I can't say enough how much a part of ClojureScript is the GCL. Here is another reference. This means that format
is a function that is part of ClojureScript.
Here's a quote from that reference:
The Google Closure Library is a javascript library developed by Google, based on a modular architecture and provides cross-browser functions for DOM manipulations and events, ajax and JSON, among other features.
It’s written specifically to take advantage of the Closure Compiler (that is used internally by the ClojureScript compiler).
And ClojureScript is built on Closure Compiler and Closure Library. In fact, ClojureScript namespaces are Closure modules.
This comment on a related jira ticket might be helpful:
Backing this one out, goog.string.format defies advanced optimization and it provides few of the capabilities of Clojure's format - which does a lot because of java.util.Formatter. Apologies for the churn, but this is a simple thing for people to stub in themselves for the little bit of functionality it actually delivers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With