Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lightweight Clojure library for simple string templating?

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.

like image 979
Johan Avatar asked Feb 17 '15 10:02

Johan


3 Answers

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 ~().

like image 156
Flux Avatar answered Nov 16 '22 00:11

Flux


There are quite a lot of templating libraries. Some general purpose ones are:

  • clostache
  • comb
  • selmer

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.

like image 32
T.Gounelle Avatar answered Nov 16 '22 01:11

T.Gounelle


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'"
like image 26
shapiy Avatar answered Nov 15 '22 23:11

shapiy