0

The following code does not work. It wants to bind the variable i at the moment the line in backquotes is seen, and of course gets an error.

const template = `this is line ${i}`

for (i = 1; i < 5; i++) {
  console.log(template);
}

Desired output:

this is line 1
this is line 2
this is line 3
this is line 4

You can see what I want: I want a late-binding template that will bind variables at the last possible moment. The example here is only a small simplification of what I really want to do, which involves an array of template strings one of which will be used.

Does JavaScript have a library for this sort of thing?

Joymaker
  • 813
  • 1
  • 9
  • 23
  • There is a special way that allows evaluating code when you want it, rather than when it's declared. No library needed. It's called "a function" - you write it, put the code you want in it, then it gets evaluated when you call it. You may think that such a powerful feature is long and cumbersome to use, yet look at this! ``templateFn = i => `this is line ${i}`;`` it is not much longer than the template itself! – VLAZ Feb 21 '23 at 22:08
  • https://stackoverflow.com/questions/30003353/can-es6-template-literals-be-substituted-at-runtime-or-reused – epascarello Feb 21 '23 at 22:10
  • Ah yes! I am more at home in Python, and in Python functions are substantial, and I would have used the % operator instead. But JavaScript functions are such lithe, light, limber little things, that they sneak up on me constantly! – Joymaker Feb 22 '23 at 12:51

1 Answers1

3

If you make the template a function and call it inside the loop, you will get the desired output:

const template = (i) => `this is line ${i}`

for (let i = 1; i < 5; i++) {
  console.log(template(i));
}

Does JavaScript have a library for this sort of thing?

Native JS only has string concatenation and template litterals, but there are tons of libraries which add sugar on top, such as mustacheJS, HandlebarsJS, EJS, etc.

blex
  • 24,941
  • 5
  • 39
  • 72