4

My question is similar to the one posted here. Essentially I would like to read a config file.json looking like this:

{
  "message": "Error in #{baseName} at #{directory}"
}

I would like to interpolate the message string using variables provided as a map / an object. Unlike in the question above, the string to be formatted is not known at compile time.

Is it possible to run a string interpolation using built-in methods in coffeescript or would I have to use mustaches or similar techniques?

hfhc2
  • 4,182
  • 2
  • 27
  • 56

2 Answers2

0

You could pretty easily wire up a very basic template engine using CoffeeScript template literals.

You would have to define your JSON as a CS file that exports:

module.exports = (context)->
  [
    some: "#{context.dynamic.content}"
  ,
    some: 'other static content'
  ]

Then, you would simply call the function with the values you want:

render = require './data'
myContext =
  dynamic: content: 'some dynamic content'

dynamicData = render(myContext)

At this point dynamicData looks like this:

[
  some: 'some dynamic content'
,
  some: 'other static content'
]
Ezra Chu
  • 832
  • 4
  • 13
-2

As per the comment by @deceze - no. The coffeescript will be compiled and executed as JS which doesn't have this string interpolation syntax. And even then, you would have to use eval(), which isn't good practice.

I would suggest the JS library spintf for on the fly string interpolation. You may be familiar with the syntax from other languages

caffeinated.tech
  • 6,428
  • 1
  • 21
  • 40
  • Template literals are rendered at runtime. This is [valid CoffeeScript](http://coffeescript.org/#try:x%20%3D%20%22%23%7BDate.now()%7D%22): `x = "#{Date.now()}"`. CS string interpolation just transpiles to JS string concatenation, so any valid JS that returns a string can be used. Also, ES6 has [template literals](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals) now. – Ezra Chu Jul 25 '17 at 06:06
  • @EzraChu, true, but the `file.json` containing the template literals isn't compiled by Coffeescript - it is evaluated at runtime by JS transpiled from the CoffeeScript source. The ES6 template literals may be an option, but as you mentioned, Coffeescript transpiles to concatenation, not ES6 interpolation. Maybe there is a flavour of Coffeescript which can do this for you though. – caffeinated.tech Jul 25 '17 at 09:01