首页 > 解决方案 > 表不从数组中导入值(Handlebars/html/javascript)

问题描述

我为从以下数组导入数据的表创建了一个车把模板。

let all_units = [
    {
        'code': 'COMP2110',
        'title': 'Web Technology', 
        'offering': 'S1'
    },  
    {
        'code': 'COMP2010',
        'title': 'Algorithms and Data Structures', 
        'offering': 'S1'
    },
    {
        'code': 'COMP2150',
        'title': 'Game Design', 
        'offering': 'S1'
    },
    {
        'code': 'COMP2320',
        'title': 'Offensive Security', 
        'offering': 'S1'
    },
    {
        'code': 'COMP2200',
        'title': 'Data Science', 
        'offering': 'S2'
    },
    {
        'code': 'COMP2250',
        'title': 'Data Communications', 
        'offering': 'S2'
    },
    {
        'code': 'COMP2300',
        'title': 'Applied Cryptography', 
        'offering': 'S2'
    },
    {
        'code': 'COMP2000',
        'title': 'Object-Oriented Programming Practices', 
        'offering': 'S2'
    },
    {
        'code': 'COMP2050',
        'title': 'Software Engineering', 
        'offering': 'S2'
    },
    {
        'code': 'COMP2100',
        'title': 'Systems Programming', 
        'offering': 'S2'
    }
];

这是主 html 页面上的我的车把模板。

        <script id="Unit_List" type="text/x-handlebars-template">
        <table>
            <tr>
            <th> Code </th>
            <th> Title </th>
            <th> Offering </th>
            </tr>
            <tr>
                {{#each unit}}
                <th> {{code}} </th>
                <th> {{title}} </th>
                <th> {{offering}} </th>
                {{/each}}
            </tr>

        </table>


        </script>

这是应该显示表格的 javascript 页面上的视图函数。

function unit_table(id, units) {
    let target = document.getElementById(id);
    let table = "<table>";

    let template= Handlebars.compile(
                                      document.getElementById("Unit_List").textContent     
                                      );
    table=template({'units': units});
    console.log(table);




    table += "</table>";
    target.innerHTML = table;
}

但是,车把模板无法将数组中的值导入表中。它只显示没有值的标题行。车把初始化可能有问题。我确保所有功能都正确导入和导出。任何帮助,将不胜感激。谢谢你。

标签: javascripthtmlarrayshandlebars.js

解决方案


推荐阅读