将jQuery模板与复杂对象一起使用并从子集合中获取值

时间:2011-01-13 14:02:41

标签: jquery templates

在我的jQuery模板中,我需要获取包含在我的数据结构的子集合中的项的值。

假设我有一个如下所示的数据结构:

    <Quote>
      <AgentName></AgentName>
      <AgentId></AgentId>
      <QuoteId></QuoteId>
      <ProductId></ProductId>
      <ProductName></ProductName>
      <Benefits>
        <Benefit>
          <Name>Benefit One</Name>
          <Description>This is benefit One</Description>
          <Value>5000000</Value>
          <ValueComment></ValueComment>
          <Excess>200</Excess>
          <ExcessComment></ExcessComment>
        </Benefit>
        <Benefit>
          <Name>Benefit Two</Name>
          <Description>This is benefit Two</Description>
          <Value>1000</Value>
          <ValueComment></ValueComment>
          <Excess>100</Excess>
          <ExcessComment></ExcessComment>
        </Benefit>
      </Benefits>
      <Price>10.99</Price>
    </Quote>

然后我可以将其转换为如下所示的JSON字符串:

[{"AgentName":null,"AgentId":null,"QuoteId":null,"ProductId":"abc","ProductName":"Standard","Benefits":[{"Name":"Benefit One","Description":"\n This is benefit One \n ","Value":5000000,"ValueComment":null,"Excess":200,"ExcessComment":null},{"Name":"Benefit Two","Description":"\n This is benefit Two\n ","Value":1000,"ValueComment":null,"Excess":100,"ExcessComment":null}],"Price":10.99}

在我的jQuery模板中,我想创建一个表格,显示产品ID,产品名称,价格和唯一的利益一的价值:

<script id="QuoteTemplate" type="text/x-jQuery-tmpl">
    <tr>
      <td valign="middle" style="width: 120px; text-align: left; font-weight:bold" class="quote-row"> ${ProductId} </td>
      <td valign="middle" style="width: 140px; text-align: center; font-weight:bold" class="quote-row"> ${ProductName} </td>

      // Somehow need to query the benefits collection to get only the value of Benefit One
      <td valign="middle" style="width: 140px; text-align: center; font-weight:bold" class="quote-row"> ${   ***ONLY BENEFIT ONE*** .value    } </td>

      <td valign="middle" style="width: 140px; text-align: center; font-weight:bold" class="quote-row"> ${Price} </td>
    </tr>
</script>   

感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

您好,以下内容对我有用:{{= Benefits [0] .Value}}

基本上,好处是一个数组,所以我们采用该数组的第一个值,这是一个好处,并显示值实体

<script id="stackTemplate" type="text/x-jQuery-tmpl">
    <tr>
      <td valign="middle" style="width: 120px; text-align: left; font-weight:bold" class="quote-row"> ${ProductId} </td>
      <td valign="middle" style="width: 140px; text-align: center; font-weight:bold" class="quote-row"> ${ProductName} </td>


                <td valign="middle" style="width: 140px; text-align: center; font-weight:bold" class="quote-row"> {{= Benefits[0].Value}} </td>


      <td valign="middle" style="width: 140px; text-align: center; font-weight:bold" class="quote-row"> ${Price} </td>
    </tr>
</script>