5

Using 2.1.3, is there a way to iterate over an array in an x-magento-template?

i.e. (below is not working):

<script id="exampleTemplate" type="text/x-magento-template">
    <div>
       <p>Name: <%- data.name -%></p>
       <ul>
       <% for(var o in data.options) { %> 
          <li><%- data.options[o] -%></li>
       <% } %>
       </ul>
   </div>
</script>

<script type="text/javascript">
    var tmpl = mageTemplate('#exampleTemplate', {
                data: {
                  name: 'My product',
                  options: ['Option 1', 'Option 2']
               }
            });
    $(exampleContainer).append(tmpl);
</script>

To end up with:

<div>
     <p>Name: My product</p>
     <ul>
        <li>Option 1</li>
        <li>Option 2</li>
     </ul>
 </div>
4
  • Do you have any error in console? for example: Uncaught SyntaxError: Unexpected token var
    – KAndy
    Jan 9, 2017 at 21:36
  • @KAndy - yes: 'underscore.js:1442 Uncaught SyntaxError: Unexpected token )(…)'.
    – dbcn
    Jan 9, 2017 at 21:50
  • Looks like you don't need underscore at start _for
    – KAndy
    Jan 9, 2017 at 21:51
  • Thx @Kandy - I'm getting a different error on the for - there's some syntax I'm missing...
    – dbcn
    Jan 9, 2017 at 22:25

1 Answer 1

6

Solved - I found this syntax in vendor/magento/module-multiple-wishlist/view/frontend/templates/behavior.phtml:

<script id="exampleTemplate" type="text/x-magento-template">
    <div>
       <p>Name: <%- data.name -%></p>
       <ul>
       <% _.each(data.options, function(item) { %> 
          <li><%- item.label -%></li>
       <% }); %>
       </ul>
     </div>
 </script>

And then convert the data.options to an array of objects:

<script type="text/javascript">
    var tmpl = mageTemplate('#exampleTemplate', {
            data: {
              name: 'My product',
              options: [
                 {label: 'Option 1'}, 
                 {label: 'Option 2'}
              ]
           }
        });
$(exampleContainer).append(tmpl);

5
  • Any idea how to do counter variable in this _.each loop? like the way we do i++ and all with PHP? Jan 10, 2023 at 13:02
  • 1
    @VirangJethva pretty sure you can pass in an index as the 2nd arg to the function() call in the _each - ie, <% _.each(data.options, function(item, index) { %>
    – dbcn
    Jan 13, 2023 at 17:27
  • I know how to loop but want to have incremental variable inside loop. @dbcn Jan 16, 2023 at 6:25
  • 1
    the value of index will increment starting from 0 @VirangJethva
    – dbcn
    Jan 17, 2023 at 17:00
  • Ohh my bad, sorry, I didn't look at that index param, thanks so much @dbcn. Jan 18, 2023 at 6:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.