Request Quote

Using loop in templates magento 2

Instead of writing the html in string and then printing the output, it better to use templates which are efficient in many ways and easy to use once you get the hang of it; specially when you need to use loops like printing data in table etc.

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 <tr> 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.

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

 

Happy coding 🙂

 

. . .

Comment

Add Your Comment

Be the first to comment.

css.php
Hire Us!
Brief us about your requirements and we'll get back to you.
Woo! Hooy!
We have just recieved your project brief and our expert will contact you shortly.
Send Again
Close