是否可以使用数组作为 jsrender 辅助函数的参数?

问题描述 投票:0回答:0

我有一些 JavaScript 代码,用于通过匹配这些相同对象中的标识属性值来从对象数组中检索属性的值。

plantArray.find(p => p.PlantCode.toUpperCase() == code.toUpperCase()).PlantName;

我想在辅助函数中使用它,这样我就可以在渲染模板时使用它。

function plantNameFromCode(code, plantArray) {
        if (plantArray)
        {
                if (typeof plantArray == "string")
                        return plantArray;

                plantname = plantArray.find(p => p.PlantCode.toUpperCase() == code.toUpperCase()).PlantName;
                return plantname;
        }
        else
        {
                return code;
        }
}

$.views.helpers({
        plantNameFromCode: plantNameFromCode
});

模板如下所示:

<script id="test-plantnamefromcode-template" type="text/x-jsrender">
        {{!-- selectedplants is an array of plant codes --}}
        {{for selectedplants itemVar="~plant"}}
                Plant Code: {{:~plant}}<BR>
                Plant Test: {{:~plantNameFromCode(~plant, "TEST")}}<BR>
                Plant Name: {{:~plantNameFromCode(~plant, plantlist)}}<BR>
        {{/for}}
</script>

数据如下所示:

var data = {
        selectedplants: ["PlantCode2", "PlantCode4"],
        plantlist: [
                {
                        PlantCode: 'PlantCode1',
                        PlantName: 'Plant Name 1'
                },
                {
                        PlantCode: 'PlantCode2',
                        PlantName: 'Plant Name 2'
                },
                {
                        PlantCode: 'PlantCode3',
                        PlantName: 'Plant Name 3'
                },
                {
                        PlantCode: 'PlantCode4',
                        PlantName: 'Plant Name 4'
                },
                {
                        PlantCode: 'PlantCode5',
                        PlantName: 'Plant Name 5'
                },
                {
                        PlantCode: 'PlantCode6',
                        PlantName: 'Plant Name 6'
                },
        ]};

我这样渲染模板:

       var template = $.templates("#test-plantnamefromcode-template");
        html = template.render(data);
        $("#main").html(html);

在渲染期间以数组作为第二个参数调用函数时,辅助函数参数 plantArray 未定义。我想知道是否可以通过这种方式将数组传递给辅助函数。

我尝试以多种方式从模板内传递数组。我使用过 ~plantlist、:~plantlist、:plantlist 和 plantlist。这些格式似乎都没有将数组传递到辅助函数中

如果我传入一个字符串变量,辅助函数就会看到它,如模板定义中的 TEST 行所示。

在将数组作为参数提供时,是否需要引用该数组?是否允许数组作为辅助函数的参数?

javascript arrays templates helper jsrender
© www.soinside.com 2019 - 2024. All rights reserved.