简体   繁体   English

如何在不使用{{#each}}或{{#if}}的情况下从Handlebars.js中的.json文件获取数据?

[英]How can I get data from a .json file in Handlebars.js without using {{#each}} or {{#if}}?

I've been using {{#each}} and {{#if}} in handlebars.js to grab data from JSON files. 我一直在handlebars.js中使用{{#each}}{{#if}}来从JSON文件中获取数据。 But I need a way to get the data without any conditions. 但是我需要一种无条件获取数据的方法。 I have no need for an {{#if}} statement and there's only one set of data so I don't need {{#each}} either. 我不需要{{#if}}语句,并且只需要一组数据,因此也不需要{{#each}} Is there a way to do this? 有没有办法做到这一点? {{#each}} works but I don't want to be using that if there's a simpler method to get a single block of data. {{#each}}但是如果有一种更简单的方法来获取单个数据块,我不想使用它。

I should note that I'm using Grunt with Handlebars and that my document calls from more than just one JSON file. 我应该注意,我正在使用Grunt with Handlebars,并且我的文档从多个JSON文件中调用。

Here is my code. 这是我的代码。

  {{data.PaymentMethod}}
  <table>
  <tr>
    <td>
      <div>Payment Method</div>
      <div>Card Number: {{CardNumber}}</div>
      <div>Card Colder: {{CardHolder}}</div>
      <div><a href="{{Link}}">Tracking</a></div>
    </td>
  </tr>
  </table>

And this is my JSON file ( data.json ). 这是我的JSON文件( data.json )。

{
"PaymentMethod": [
        {
            "CardNumber": "****",
            "CardHolder": "John Doe",
            "Link": "http://www.test.com"
        }
    ]
}
<div>Card Number: {{data.PaymentMethod.0.CardNumber}}</div>
<div>Card Colder: {{data.PaymentMethod.[0].CardHolder}}</div>

You should be able to access it like so. 您应该能够像这样访问它。 Because data.PaymentMethod is an array you have to access the first object in that array. 因为data.PaymentMethod是一个数组,所以您必须访问该数组中的第一个对象。

You can use the #with helper to step into the array: 您可以使用#with帮助器进入数组:

{{#with PaymentMethod.[0]}}
    <div>Payment Method</div>
    <div>Card Number: {{CardNumber}}</div>
    <div>Card Colder: {{CardHolder}}</div>
    <div><a href="{{Link}}">Tracking</a></div>
{{/with}}

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

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