Instead of writing the HTML in string and then printing the output, it is better to use templates that are efficient in many ways and easy to use once you get the hang of it; especially when you need to use loops like printing data in table, etc. in magento 2.
First, write the template in your phtml file.
<script id="options-template" type="text/x-magento-template"> <table class="data-grid data-grid-draggable"> <thead> <tr> <td><input type='checkbox'></td> <td>Title</td> </tr> </thead> <tbody> <% _.each( target, function(i) {%> <tr class="data-row"> <td class='wk-tab-check'><input type='checkbox' value='<%= i.value %>' class='checkbox' name="checkbox[]"> <td class='wk-tab-title'><input type='text' name='title-<%= i.value %>' id='title-<%= i.value %>' value='<%= i.label %>'/></td> </tr> <% }); %> </tbody> </table> </script>
Write a div to print the output.
<div id="output"></div>
As you can see, each loop has been used to print the data in repeatedly.
Suppose the data is in array form
Array ( [1] => Array ( [value] => 1 [label] => Bitter ) [2] => Array ( [value] => 2 [label] => Sour ) [3] => Array ( [value] => 3 [label] => Sweet ) )
Now in the js file, prepare the data to print.
require([ 'jquery', 'underscore', ], function ($, _) { var data = { target:response }; var template = _.template( $("#options-template").text() ); $("#output").html( template(data) ); });
This will print the data in loop like shown in the picture
Be the first to comment.