Search code examples
jquerytemplatesjquery-pluginsjquery-templates

jquery tmpl accessing sub elements in nestd array


I am using jQuerys "tmpl" plugin for templates. Now i have an array with elements that are arrays as well and i have to access specific elements.

i.e. the array would be:

var arr = {
  'id':23422,
  'title':'example',
  'images': {'small':'34fge.jpg','original':'dfsdf354.jpg'}
};

And now in the temple i'd like to access arr[images][small] but it doesn't work. What i am trying is:

<div>
  <h3>${title}</h3>
  <img src="${arr}{images}{small}" />
</div>

Anyone any help/ideas?


Solution

  • Use <img src="${images.small}" /> that will give the following markup:

    <div>
      <h3>example</h3>
      <img src="34fge.jpg">
    </div>
    

    In fact, the images property isn't a nested array but a object with properties.

    But if you really want to loop through a nested array, then you should use a nested template and change your syntax a little bit (note the [] around images property):

    Javascript

    var arr = {
        'id': 23422,
        'title': 'example',
        'images': [
            { 'small': '34fge.jpg', 'original': 'dfsdf354.jpg' },
            { 'small': '35fge.jpg', 'original': 'dfsdf.jpg' }
        ]
    };
    

    Templates

    <script id="template" type="text/x-jquery-tmpl">
       <div>
         <h3>${title}</h3>
         {{tmpl(images) "#imagesTemplate"}}
       </div>
    </script>
    <script id="imagesTemplate" type="text/x-jquery-tmpl">
         <img src="${small}" />
         <img src="${original}" />
    </script>