0

I am trying to use the template literals to natively achieve something similar to handlebars.

Here is my code:

let myTemplate = '<div class="tab" data-group="${id}">${name}</div>';

let doYourMagic = function(){
    let tabInfo = {
        id: 1234,
        name: "Alex"
    }

    let { id, name } =  tabInfo;

    console.log(myTemplate);
} )

now, the issue is that when i run the doYourMagic function i get:

<div class="tab" data-group="${id}">${name}</div>

However, if I console.log one of those variables I get the correct value (for example, console.log(name) would get me my name value).

I would like to get the string properly interpolated, what am I doing wrong?

akmur
  • 1,465
  • 2
  • 24
  • 37
  • I can't tell correctly from SO but you seem to be using the single quote (`'`) for your string. For string interpolation you need to use the little slanted quote thing. The same one you use to highlight code in SO's comments. ``` [see](https://jsfiddle.net/bjpa89ou/2/) – ste2425 May 16 '16 at 10:46
  • Thanks, that's it! So stupid! – akmur May 16 '16 at 10:51
  • No problem happens to us all :), Full answer in question linked below. – ste2425 May 16 '16 at 10:52
  • Possible duplicate of [ES6 / ECMA6 template literals - not working](http://stackoverflow.com/questions/37245679/es6-ecma6-template-literals-not-working) – CodingIntrigue May 16 '16 at 10:53

1 Answers1

0

Instead of declaring your string with ' theString ', you have to use the template literals notation like this ` theString `.

So your code become:

let myTemplate = `<div class="tab" data-group="${id}">${name}</div>`;
//>  <div class="tab" data-group="1234">Alex</div>

You can also simplify it into this for example, that will also do the job:

let tabInfo = {
    id: 1234,
    name: "Alex"
};
console.log(`<div class="tab" data-group="${tabInfo.id}">${tabInfo.name}</div>`);
NatNgs
  • 874
  • 14
  • 25