Categories
Blog Tech

Binding JSON data dynamically from ajax/promise/observable request to pug template

I was struggling to loop over ajax response to pug, with a lot of scratching head on google and Github, got a clue to use ES6 template to create cart list items from response data and append its HTML back to section container of HTML, here is sample code below.

I have also tried out achieved the same via pug mixin (commented code below, not successful) but not sure how to pass JS object variable to mixin as it’s not accepting response data as an object parameter.

Found similar doing here https://codepen.io/anon/pen/GeQKxp
it has pass individual object literal to the mixin, but if we pass the object variable created in JS and pass to the mixin, it doesn’t work, not sure how to turn around with it!

Hope this example code give you a hint.

I am not a professional writer of content, therefore treat this as general information for help on the similar issue anyone face with pug and json data.

//- cart.pug template

block append headScript
    script(src='./../js/scripts.js')
    script.
        myApp.fetchCartItems().subscribe(
            data => {
                if ('productsInCart' in data){
                    const cartItemsData = data.productsInCart;
                    const cartItemsTemplate = cartItemsData.map(item => {
                        function getColors(colors) {
                            return colors.length ? colors.map( color => `<span>${color.name}</span>`) : 'standard color'
                        }
                        function getSizes(sizes) {
                            return sizes.length ? sizes.map( size => `<span>${size.code}</span>`).join(' ').toUpperCase() : 'standard size'
                        }
                        return `<div class="row cart-item-row">
                                <div class="col-md-6">
                                    <img src="../images/T${item.p_id}.jpg" class="cart-thumb" />
                                    <div class="cart-item-detail">
                                        <h3>${item.p_name}</h3>
                                        <label>Style #: ${item.p_style}</label>
                                        <label>Colour: ${getColors(item.p_available_options.colors)}</label>
                                    </div>
                                    <div class="cart-actions">
                                        <a href="javascript:void(0)" class="jsEdit">Edit</a>
                                        <a href="javascript:void(0)">X Remove</a>
                                        <a href="javascript:void(0)">Save for Later</a>
                                    </div>
                                </div>
                                <div class="col-md-2 text-center">${getSizes(item.p_available_options.sizes)}</div>
                                <div class="col-md-2 text-center">
                                    <input type="text" name="txtQty${item.p_quantity}" id="txtQty${item.p_quantity}" value="${item.p_quantity}" class="form-control qty-input" />
                                </div>
                                <div class="col-md-2 text-right price-text"><sup>$</sup>${item.p_price}</div>
                            </div>
                            `
                    });

                    document.getElementById('cartItemContainer').innerHTML = cartItemsTemplate;
                }
            },
            err => {
                console.error('Subscribe Error', err);
            },
            () => {
                console.info('Subscribe complete');
            }
        );

section(class='cart-content' id='cartItemContainer' data-json= cartItems) cartItemContainer

//- mixin cartItemsMixin(cartItems)
//-     div(id='cartItemContainer' data-json= cartItems) cartItemContainer
//-     //- div= #{JSON.stringify(cartItems)}
//-     div(data-json= cartItems)
//-     section.cart-content
//-         .row.cart-item-row
//-             .col-md-6
//-                 img.cart-thumb(src='../images/T1.jpg')
//-                 .cart-item-detail
//-                     h3 Solid green cotton tshirt
//-                     label Style #: MS13KT1906
//-                     label Colour: Blue
//-                 .cart-actions
//-                     a.jsEdit(href='javascript:void(0)') Edit
//-                     a(href='javascript:void(0)') X Remove
//-                     a(href='javascript:void(0)') Save for later
//-             .col-md-2.text-center S
//-             .col-md-2.text-center
//-                 input.form-control.qty-input(type='text', name='txtQty1', id='txtQty1', value='1')
//-             .col-md-2.text-right.price-text
//-                 sup $ 
//-                 | 11.00
//- +cartItemsMixin(cartItemsData)