I'm looking for a (preferably small) Clojure library that is available in clojars which allows me to replace simple templates in strings such as:
"Hello my name is ${name}"
where ${name}
should be replaced by the template engine. In Java I usually use JMTE that works perfectly. I know that I can probably use it from Clojure as well but I wonder if there's something that is more Clojure friendly/idiomatic.
You can use the <<
string interpolation macro from the core.incubator project.
To use it, add [org.clojure/core.incubator "0.1.4"]
as a dependency in your project.clj
file. (Note: check core.incubator's GitHub page for the latest installation instructions.)
Example use:
(ns example
(:require [clojure.core.strint :refer [<<]]))
(def my-name "XYZ")
(<< "My name is ~{my-name}.")
; Returns: "My name is XYZ."
(let [x 3
y 4]
(<< "~{x} plus ~{y} equals ~(+ x y)."))
; Returns: "3 plus 4 equals 7."
Note the difference between the use of curly braces ~{}
and parentheses ~()
.
There are quite a lot of templating libraries. Some general purpose ones are:
Note: If you just need to have some clever formatting, you have the standard library clojure.pprint with the cl-format
function and clojure.core/format
which is the wrapper around java.util.Formatter
.
Though not a library, found this example in Clojure, the Essential Reference book.
replace
could be used to implement a simple textual substitution system. An input string contains special placeholders that the system can identify and replace from a list of known substitutions:
(def text "You provided the following: user {usr} password {pwd}")
(def sub {"{usr}" "'rb075'" "{pwd}" "'xfrDDjsk'"})
(transduce
(comp
(replace sub)
(interpose " "))
str
(clojure.string/split text #"\s"))
;; "You provided the following: user 'rb075' password 'xfrDDjsk'"
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