Using well-structured, script-generated HTML is crucial for effective theme development.

Topic summary

A developer sought confirmation on the correct approach for displaying cart data in a Liquid theme file, sharing JavaScript code for a fetchCart() function that retrieves and renders cart items.

Issue Identified:
The original code contained reversed/garbled text in several sections, making portions of the HTML structure and error handling difficult to read.

Solution Provided:
A community member offered a refactored version with three key improvements:

  • Performance optimization: Building HTML in a cartItemsHTML variable and updating innerHTML once, rather than repeatedly inside the loop
  • Enhanced error handling: Adding checks to ensure cart.items exists before processing, with clearer console error messages
  • Code readability: Cleaning up the structure for easier debugging

Outcome:
The developer accepted the solution and planned to implement the suggested improvements. The discussion concluded with encouragement to mark the response as helpful.

Summarized with AI on November 5. AI used: claude-sonnet-4-5-20250929.

Please confirm , I have developed theme it’s close to complete , kindly share it’s correct way to show data’s on liquid file .Kindly share suggestions

Example code

function fetchCart() {
fetch(‘/cart.js’)
.then(response => response.json())
.then(cart => {
console.log(‘Cart data:’, cart);

const cartItemsList = document.getElementById(‘cart-items-list1’);
const totalElement = document.getElementById(‘cart-total1’);

if (cartItemsList && totalElement) {
$(‘.collections_info’).show();
cartItemsList.innerHTML = ‘’;
let total = 0;

if (cart.items.length === 0) {

document.getElementById(‘cart_totalinfo’).style.display=“none”;
document.getElementById(‘collections_info’).style.display=“block”;

} else {
$(‘.collections_info’).hide();

cart.items.forEach(item => {
total += item.line_price;

cartItemsList.innerHTML += `

Rs. ${(item.price / 100).toFixed(2)}
${item.options_with_values.map(option => `
${option.name}:
${option.value}
`).join('')}
- ${item.quantity} +
Rs. ${(item.line_price / 100).toFixed(2)}
{{ 'sections.cart.remove' | t }}
`; }); }

totalElement.textContent = Sub total: Rs. ${(total / 100).toFixed(2)};
} else {
console.error(‘Cart items list or total element not found.’);
}
})
.catch(error => console.error(‘Error fetching cart:’, error));
}

1 Like
function fetchCart() {
    fetch('/cart.js')
        .then(response => response.json())
        .then(cart => {
            console.log('Cart data:', cart);

            const cartItemsList = document.getElementById('cart-items-list1');
            const totalElement = document.getElementById('cart-total1');

            if (cartItemsList && totalElement) {
                // Display cart information if elements exist
                $('.collections_info').show();
                cartItemsList.innerHTML = '';
                let total = 0;
                let cartItemsHTML = '';

                if (cart.items && cart.items.length === 0) {
                    // Handle case when cart is empty
                    document.getElementById('cart_totalinfo').style.display = "none";
                    document.getElementById('collections_info').style.display = "block";
                } else {
                    // Hide collections info when there are items in the cart
                    $('.collections_info').hide();

                    cart.items.forEach(item => {
                        total += item.line_price;

                        cartItemsHTML += `
                            

                                

                                    

                                        
                                            

                                                
                                            

                                        
                                    

                                    
                                        

                                            
                                                ${item.handle}
                                            
                                        

                                        Rs. ${(item.price / 100).toFixed(2)}

                                        
                                            ${item.options_with_values.map(option => `
                                                

                                                    
${option.name}:

                                                    ${option.value}

                                                

                                            `).join('')}
                                        

                                        
                                            

                                                
                                                ${item.quantity}
                                                
                                            

                                        

                                        
                                            Rs. ${(item.line_price / 100).toFixed(2)}
                                        

                                        
                                    

                                

                            

                        `;
                    });

                    // Update the innerHTML of the cart item list after processing all items
                    cartItemsList.innerHTML = cartItemsHTML;
                }

                // Update the total amount
                totalElement.textContent = `Sub total: Rs. ${(total / 100).toFixed(2)}`;
            } else {
                // Log an error if elements are not found
                console.error('Cart items list or total element not found.');
            }
        })
        .catch(error => console.error('Error fetching cart:', error));
}

You can try this code

  • Optimized performance: Instead of updating the innerHTML inside the loop, all HTML is built up in cartItemsHTML and set in one go.

  • Checked for cart.items existence: Ensures that cart.items is available before processing.

  • Improved error handling: Logs an error message if the necessary elements aren’t found to help with debugging.

Thank you so much for your help! I’ll be updating my code with these improvements.

1 Like

Glad to help you. Have a good day.

  • Please press ‘Like’ if you find it helpful. Thank you.
1 Like