Existing approaches for string formatting a template with a map?

I am going to store string email templates in my database; the program will select a template and provide a map to replace the template variables within the string. This seems like an obvious thing to do (it is nearly accomplished with good 'ol format), but I have yet to spot any clear libraries or functions that take care of it. Below is the use I have in mind; anyone know of existing solutions here?

(deftest templating
  (let [replacement-map {:user "Gandalf"
                         :spell "Incendio"
                         :species "Borg"}
        replacement-string ":user, a :species, cast :spell"]
    (is (= (unwritten-function replacement-string replacement-map)
           "Gandalf, a Borg, cast Incendio"))))

We use https://github.com/yogthos/Selmer very heavily at work for exactly this scenario. Selmer provides Django-like facilities (conditionals, basic loops, etc).

1 Like

You can use clojure.string/replace. The regex would match “any placeholder” and the replacement would be a fn that looks up the placeholder name in the map.

Here’s a few extras:

And all the ones listed on clojure-toolbox.com

Template Languages

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.