下划线js

时间:2017-07-28 12:33:44

标签: javascript underscore.js

您好我正在尝试在Underscore.js中探索模板

到目前为止,我创建了这个模板字符串:

  var student = "<% _.each(students, function(elem, index, list){ %>" +
    "<h1>" + "<%= elem.lastname %>" + " " + "<%= elem.firstname %>" + "</h1>" +
    "<br/> <h2>" + "<%= elem.school %>" + "</h2>" +
  "<% }); %>";

然后在我的代码中我这样称呼它:

  function appendTemplateData(dataString) {
        let container = document.getElementById("container");
        container.innerHTML = container.innerHTML + dataString;
    }

 var result = _.template(student, students);
  appendTemplateData(result);

在这一部分:

var result = _.template(student, students);

我的模板变量是学生,而我有一个外部js文件w / c是一个带有ff信息的对象数组:

var students = [
    {
        "firstname": "Woody",
        "lastname" : "Johnson",
        "school" : "Bloc",
        "grade" : 12,
        "midterm_score": 75,
        "final_score": 85
    },
    {
        "firstname" : "Jerry",
        "lastname" : "Jones",
        "school" : "Hack Reactor",
        "grade" : 10,
        "midterm_score": 50,
        "final_score": 65
    }
];

运行我的代码后,它会返回此错误:

function (n){return o.call(this,n,m)}

我不确定这意味着什么。有帮助吗?为什么会出现这样的错误?我该如何解决?

1 个答案:

答案 0 :(得分:1)

正确的调用应该是:_.template(学生)(学生),更像你编译模板然后你调用它...你得到的函数是编译一个,不是错误

 var student = "<% _.each(students, function(elem, index, list){ %>" +
    "<h1>" + "<%= elem.lastname %>" + " " + "<%= elem.firstname %>" + "</h1>" +
    "<br/> <h2>" + "<%= elem.school %>" + "</h2>" +
  "<% }); %>";
  
  var students = [
    {
        "firstname": "Woody",
        "lastname" : "Johnson",
        "school" : "Bloc",
        "grade" : 12,
        "midterm_score": 75,
        "final_score": 85
    },
    {
        "firstname" : "Jerry",
        "lastname" : "Jones",
        "school" : "Hack Reactor",
        "grade" : 10,
        "midterm_score": 50,
        "final_score": 65
    }
];

  function appendTemplateData(dataString) {
        let container = document.getElementById("container");
        container.innerHTML = container.innerHTML + dataString;
    }

 var compiledTemplated = _.template(student);
 var result = compiledTemplated({students: students});
  appendTemplateData(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>


<div id="container">
</div>