Trying to wrap my head around Javascript. If I have a declared variable with template literals, for example:
var templateObject = `Student name is ${filteredJSONExample.name} and student age is ${filteredJSONExample.age}.`
This works as per below:
But, if I have a JSON data for example, containing template literal wrapped string as its value, it doesn't work compared to the above.
var templateDataObject = [
{"type": "template", "fields": {"template": "`Student name is ${filteredJSONExample.name} and student age is ${filteredJSONExample.age}`"}}
]
How can I insert variable(s) value using template literals should the case be where the template is coming from JSON data, or is there a correct way to actually do this?
Full code below:
<html>
<head>
<title>JS Select Exercise</title>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BmbxuPwQa2lc/FVzBcNJ7UAyJxM6wuqIj61tLrc4wSX0szH/Ev+nYRRuWlolflfl" crossorigin="anonymous">
</head>
<body>
<div class="container">
<hr/>
<div class="row">
<div class="col-lg-6">
<div class="card">
<div class="card-body">
<select class="form-control" id="select_demo" onchange=onKidChange(this)></select>
<br/>
<h3 id="agevalue"></h3>
<br/>
<h3 id="statement"></h3>
<button class="btn btn-sm btn-primary" onclick=printStatement()>Print Statement</button>
<br/><br/>
<button class="btn btn-sm btn-info" onclick=printAnotherStatement()>Print Another Statement</button>
</div>
</div>
</div>
</div>
</div>
</body>
<script>
var jsonDataObject = [
{"model": "A", "identifier": 1, "fields": {"name": "Stan", "age": "12"}},
{"model": "B", "identifier": 2, "fields": {"name": "Brett", "age": "14"}}
]
var filteredJSONExample = jsonDataObject[0]['fields']
var templateDataObject = [
{"type": "template", "fields": {"template": "`Student name is ${filteredJSONExample.name} and student age is ${filteredJSONExample.age}`"}}
]
var stripToTemplate = templateDataObject[0]['fields'].template
var templateObject = `Student name is ${filteredJSONExample.name} and student age is ${filteredJSONExample.age}.`
var kidModels = document.getElementById("select_demo")
var kidAge = document.getElementById("agevalue")
var kidStatement = document.getElementById("statement")
function setup(){
for(var a = 0; a < jsonDataObject.length; a++){
var option = document.createElement("option")
option.innerHTML = jsonDataObject[a]["fields"].name
option.value = jsonDataObject[a]["fields"].age
kidModels.options.add(option)
kidAge.innerHTML = kidModels.value
kidTry = kidModels.value
}
}
function onKidChange(selected){
for(var a=0; a < jsonDataObject.length; a++){
if(selected.value == jsonDataObject[a]["fields"].age){
kidAge.innerHTML = selected.value
kidTry = selected.value
}
}
}
function printStatement(){
kidStatement.innerHTML = templateObject
}
function printAnotherStatement(){
kidStatement.innerHTML = stripToTemplate
}
window.onload = setup
</script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-b5kHyXgcpbZJO/tY9Ul7kGkf1S0CWuKcCD38l8YkeH8z8QjE0GmW1gYU5S9FOnJ0" crossorigin="anonymous"></script>
</html>
Thanks in advance for any suggestions that would help me on this!
When you write:
"`Hello, my name is ${name}`"
Is a good old plain regular string with value:
`Hello, my name is ${name}`
No interpolation, no magic. It's a regular string that contains some value that can be whatever.
JSON & template literals aren't really compatible in the sense that JSON keys & values must be plain strings, not template literals, so, you'll likely need to use one or another but without mixing them.
If you want to dynamically print some data inside plain strings, one of the options would be to put placeholders inside plain strings & then replace those placeholders. It could look something like this:
const message = "Hello, my name is $name$!";
message.replaceAll("$name$", "Joe");
// Hello, my name is Joe!
Chrome extensions API uses the exact same approach for i18n, you can see what underlying JSON structure looks like in the docs for a reference.