简体   繁体   English

把手,从另一个JavaScript文件遍历数组

[英]Handlebars, looping over array froma different javascript file

Within myjavascript.js, I have an array like so: 在myjavascript.js中,我有一个像这样的数组:

games = [{name: "football"},{name:"basketball"}];

Within my games.handlebars I have included my javascript file at the top of the page as normal. 在我的games.handlebars中,我正常情况下已在页面顶部添加了我的javascript文件。 I want to formulate a table like so: 我想像这样制定一张桌子:

{{#if games}}
  {{#each games}}
    <tr>{{name}}</tr>
  {{/each}}
{{#else}}
  <h1> No games </h1>
{{/if}}

I always seem to hit the else statement, it thinks games is empty. 我似乎总是碰到else语句,它认为游戏是空的。 In the java-script console in my browser I can type games and it shows the object, i can see all the data in it. 在浏览器的Java脚本控制台中,我可以键入游戏,它显示了对象,我可以看到其中的所有数据。

What is it that I am doing wrong? 我做错了什么?

You're not ending your each statement, also each iteration in the loop references to this . 您不会结束each语句,循环中的每个迭代都将引用this You should also use games.length instead of just games to check if the array contains values. 您还应该使用games.length而不是仅仅使用games来检查数组是否包含值。

{{#if games.length}}
  {{#each games}}
    <tr>{{this.name}}</tr>
  {{/each}}
{{else}}
  <h1> No games </h1>
{{/if}}

each also has an else , which shows if the array is empty. each都有一个else ,它显示数组是否为空。

{{#each games}}
  <tr>{{this.name}}</tr>
{{else}}
  <h1> No games </h1>
{{/each}}

Thank you for your help. 谢谢您的帮助。

The problem was actually quite interesting. 这个问题实际上很有趣。 I'm using Handlebars through NodeJS and Express. 我正在通过NodeJS和Express使用把手。 NodeJS is installed and imported through node server side as well as in my front end pages by including the handlebars js file. 通过包含handlebars js文件,可以通过节点服务器端以及在我的前端页面中安装和导入NodeJS。

This caused an interesting conflict, When I was pulling in the handlebars template from my pages from front end java script, the back end was actually evaluation the handlebars {{}} bracket statements first. 这引起了一个有趣的冲突,当我从前端Java脚本从页面中提取把手模板时,后端实际上首先评估了把手{{}}括号语句。 As my values didn't exist at that point, it was returning HTML that did not include my handlebars {{}} brackets. 由于那时我的值不存在,因此返回的HTML不包含我的车把{{}}括号。 This then meant the front end java script had nothing to evaluate. 然后,这意味着前端Java脚本没有任何要评估的内容。

The way I got around this was from this stackoverflow post . 我解决这个问题的方法来自于这个stackoverflow帖子 Basically I had to escape the handlebars brackets like this: \\ {{}}. 基本上,我必须像这样逃避车把括号:\\ {{}}。 This then stopped server side from evaluating them before they are passed to the client side. 然后,这会阻止服务器端在将它们传递给客户端之前对其进行评估。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM