3

Let me explain my actual problem. I have a template string which could look like this:

/${name}
  get
  post
  /{id}
    get
    /file-content
      get
      post

The indentation has to remain untouched.

Now if I were to use such a template string it might look like this:

function test(arr) {
    let ret = []
    arr.forEach(
        function(name) {
            return `/${name}
  get
  post
  /{id}
    get
    /file-content
      get
      post`
            return ret
        }
    )
}

Looks pretty ridiculous, right? I could of course put extra spaces into my template to match my code indentation, but then I'd have to perform unnecessary operations on the string afterwards to normalize it again.

So my idea was to move the template string to an external file and require that file whenever I need the template string.
But require can't be used for that problem because it's nothing more than a text file and I certainly don't want to read that file from disk every time I need it and perform an eval on it.

I could think of several workarounds for this problem, but I just cannot seem find a satisfying solution.

Forivin
  • 14,780
  • 27
  • 106
  • 199

1 Answers1

1

How about this:

// template.js
module.exports = name => `
/${name}
  get
  post
  /{id}
    get
    /file-content
      get
      post
`.trim()

// app.js
const template = require('./template')('name');
robertklep
  • 198,204
  • 35
  • 394
  • 381
  • That's just one of the workarounds. I just don't want to call trim or anything on my template. I feel like there should be a way around that. It would also add a lot of maintenance work when adding more variables to the template string. – Forivin Sep 07 '16 at 12:46
  • 1
    If you add line-breaks at the beginning and the end, you should better mask them, than trimming. add a backslash at the end of the first line, and after post – Thomas Sep 07 '16 at 12:47
  • @Thomas yeah that was my initial solution as well, but I dismissed it because it's ugly – robertklep Sep 07 '16 at 12:48
  • then I'd rather use/write some post-processing step to convert the plain template into a script; maybe even concatenating all template files into a single templates-module – Thomas Sep 07 '16 at 12:52
  • @Thomas me too, but it's a bit unclear what it or isn't a good solution in the eyes of the OP. – robertklep Sep 07 '16 at 12:56