0

Consider the following snippet I tried:

<script>
    for (var key in photoList) {
        if(key == photoList[key].id) {
            var res =  `<li id="thumbnail-`+key+`">
                            <div class="thumbnail `+(product.photo == photoList[key].id)+` ? 'thumbnail-main' : ''">
                                ...
                            </div>
                        </li>`;
        }
    }
</script>

I try like that, but it did not work? How can I do it?

Andrew Li
  • 55,805
  • 14
  • 125
  • 143
moses toh
  • 12,344
  • 71
  • 243
  • 443

4 Answers4

8

When you enclose a string with grave marks (`), it allows for interpolated expression over string concatenation, called a template literal which is new in ES2015. Your ternary operator is an expression, so you can use ${expr} notation in string interpolation to interpolate an expression. Since you're already using template literals, there's no reason to do concatenation, thus:

var res = `<li id="thumbnail-${key}">
             <div class="thumbnail ${product.photo == photoList[key].id ? 'thumbnail-main' : ''}>
               ...
             </div>
           </li>`;

Anywhere you want to use string concatenation of an expression, you can just use interpolation. So instead of:

'1 + 1 = ' + (1 + 1)

You can do:

`1 + 1 = ${1 + 1}`

Because 1 + 1 is an expression.

Andrew Li
  • 55,805
  • 14
  • 125
  • 143
  • Seems you can help me. Look at this : https://stackoverflow.com/questions/44665670/how-can-i-solve-uncaught-syntaxerror-unexpected-identifier-in-string-javascript – samuel toh Jun 21 '17 at 02:49
0

You were doing it ok, but missing the string concatenation

<script>
for (var key in photoList) {
    if(key == photoList[key].id) {
        var res =  `<li id="thumbnail-`+key+`">
                        <div class="thumbnail `+(product.photo == photoList[key].id ? 'thumbnail-main' : '') + `">
                            ...
                        </div>
                    </li>`;
    }
}

nicowernli
  • 3,250
  • 22
  • 37
0

It should be:

<script>
    for (var key in photoList) {
        if(key == photoList[key].id) {
            var res =  '<li id="thumbnail-'+key+'"><div class="thumbnail ' + ((product.photo == photoList[key].id)+ ? 'thumbnail-main' : '') + ">
                                ...
                            </div>
                        </li>';
        }
    }
</script>
teo van kot
  • 12,350
  • 10
  • 38
  • 70
  • Seems you can help me. Look at this : https://stackoverflow.com/questions/44665670/how-can-i-solve-uncaught-syntaxerror-unexpected-identifier-in-string-javascript – samuel toh Jun 21 '17 at 02:49
0
for (var key in photoList) {
  if (key === photoList[key].id) {
    var res =  `
      <li id="thumbnail-${key}">
      <div class="thumbnail ${
        (product.photo === photoList[key].id) ? 'thumbnail-main' : ''
      }">
      ...
      </div>
      </li>`;
  }
}
PeterMader
  • 6,987
  • 1
  • 21
  • 31