Javascript 模板文字在声明为变量时有效,但在作为 json 模板传递时无效

Javascript template literals work when declared as a variable, but not when passed as a json template

试图让我的头脑围绕 Javascript。如果我有一个带有模板文字的声明变量,例如:

        var templateObject = `Student name is ${filteredJSONExample.name} and student age is ${filteredJSONExample.age}.`

其工作原理如下:

但是,如果我有一个 JSON 数据,例如,包含模板文字包装字符串作为其值,与上面相比它不起作用。

var templateDataObject = [
            {"type": "template", "fields": {"template": "`Student name is ${filteredJSONExample.name} and student age is ${filteredJSONExample.age}`"}}
        ]

如果模板来自 JSON 数据,我如何使用模板文字插入变量值,或者是否有正确的方法来实际执行此操作?

完整代码如下:

<html>
    <head>
        <title>JS Select Exercise</title>
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/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/bootstrap@5.0.0-beta2/dist/js/bootstrap.bundle.min.js" integrity="sha384-b5kHyXgcpbZJO/tY9Ul7kGkf1S0CWuKcCD38l8YkeH8z8QjE0GmW1gYU5S9FOnJ0" crossorigin="anonymous"></script>
</html>

提前感谢任何对我有帮助的建议!

当你写:

"`Hello, my name is ${name}`"

是一个很好的旧普通字符串,其值为:

`Hello, my name is ${name}`

没有插值,没有魔法。它是一个常规字符串,包含一些可以是任何值的值。

JSON 和模板文字在 JSON 键和值必须是 纯字符串 而不是模板文字的意义上并不真正兼容,所以,您可能需要使用一种或另一种,但不要混合使用。

如果您想在纯字符串中动态打印一些数据,一种选择是将占位符放在纯字符串中,然后替换这些占位符。它可能看起来像这样:

const message = "Hello, my name is $name$!";

message.replaceAll("$name$", "Joe");
// Hello, my name is Joe!

Chrome extensions API 对 i18n 使用完全相同的方法,您可以在文档中查看 underlying JSON structure looks like 以供参考。