26
votes

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?

2
I would have thought that clojure.pprint/cl-format would be available in Clojurescript. It's an alternative to Clojure's Java-based format. In a quick test I did, clojure.pprint did not seem to be available in Clojurescript, but I don't know why it wouldn't be.Mars
If i remember correctly, cl-format is in cljs.pprint namespace in clojurescriptleetwinski

2 Answers

25
votes

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.

19
votes

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.