Search code examples
clojureclojurescriptgoogle-closure-library

ClojureScript format string with goog.string.format doesn't substitute


I'm trying to format a color in hex for use in HTML, running ClojureScript in the browser.

Here's my "format" function.

(defn gen-format [& args] (apply gstring/format args) )

in a "strings" namespace where I've required the goog.string library with :

(:require [goog.string :as gstring] [goog.string.format :as gformat])

But when I try to call it from javascript :

document.write(mypackage.strings.gen_format("#%x%x%x",0,0,0));

it just returns #%x%x%x

It's not crashing. But the goog format function doesn't seem to be substituting the values in. Am I doing something wrong here?


Solution

  • What does %x do?

    Looking at format source sorce, it only supports s, f, d, i and u:

    var formatRe = /%([0\-\ \+]*)(\d+)?(\.(\d+))?([%sfdiu])/g;
    

    This seems to be working well for me:

    mypackage.strings.gen_format("#%d%d%d", 0, 0, 0)
    

    UPDATE: If you need to render a string with color, how about these:

    (defn hex-color [& args]
      (apply str "#" (map #(.toString % 16) args))
    
    (defn hex-color [r g b]
      (str "#" (.toString r 16) (.toString g 16) (.toString b 16))