I have a simple ajax request returning some data and then inserting into a template literal. I was wondering if it it possible to insert an 'if' statement inside the template?
Essentially to add a further line of code, if the json object has a 5th color.
$.ajax({ url: 'http://localhost:8888/ColourCatchr%202/app/search.php' }).done(function(results){ var res = jQuery.parseJSON(results); console.log(res); $.each(res,function(index,result){ $('.palettes').append(` <div class="panel panel-default"> <div class="panel-heading"> <h3 class="panel-title">${result.name}</h3> </div> <div class="panel-body"> <div class="col-md-12 colors"> <div class="color" style=background-color:#${result['color 1']}><h6>${result['color 1']}</h6></div> <div class="color" style=background-color:#${result['color 2']}><h6>${result['color 2']}</h6></div> <div class="color" style=background-color:#${result['color 3']}><h6>${result['color 3']}</h6></div> <div class="color" style=background-color:#${result['color 4']}><h6>${result['color 4']}</h6></div> ${if(result['color 5']){ <div class="color" style=background-color:#${result['color 5']}><h6>${result['color 5']}</h6></div> } } <div class="color" style=background-color:#${result['color 5']}><h6>${result['color 5']}</h6></div> <p>on hover change to translucent background and black text for ecah color</p> </div> </div> <div class="panel-footer"> <a class="btn btn-info btn-lg" href="update.html?id=${result.id}">Edit</a> <a class="btn btn-danger btn-lg">Delete</a> </div> </div>` ) }) })
You can't write anything that's not a simple expression inside of a template literal, so no if statements or loops. You can use ternary expressions, however, if you need to make a choice: var quantity = 14; var cart = `You have ordered ${quantity} ${quantity > 1 ? "wheels" : "wheel"} of cheese.
The basic syntax of JavaScript template literalsUsing the backticks, you can freely use the single or double quotes in the template literal without escaping.
To create a template literal, instead of single quotes ( ' ) or double quotes ( " ) quotes we use the backtick ( ` ) character. This will produce a new string, and we can use it in any way we want.
A string literals are either enclosed in the single quotation or double quotation as ( ' ) and ( “ ) respectively and to concatenate two or more string we can use + operator. Examples for string are “hello”, “hello world”, “123”, “hello” + “world” etc.
You'll need to move your logic into a function or use the ternary operator:
`${result['color 5'] ? 'color 5 exists!' : 'color 5 does not exist!'}`
Additional example based on comment:
`${result['color 5'] ? `<div class="color" style=background-color:#${result['color 5']}><h6>${result['color 5']}</h6></div>` : ''}`
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With