Reading list Switch to dark mode

    Using loop in templates magento 2

    Updated 26 March 2024

    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

    Searching for an experienced
    Magento 2 Company ?
    Find out More
    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

    paul_blog_loop_template

    . . .

    Leave a Comment

    Your email address will not be published. Required fields are marked*


    Be the first to comment.

    Back to Top

    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home