Our Partner & Developer boards on the community are moving to a brand new home: the .dev community forums! While you can still access past discussions here, for all your future app and storefront building questions, head over to the new forums.

We're moving the community! Starting July 7, the current community will be read-only for approx. 2 weeks. You can browse content, but posting will be temporarily unavailable. Learn more

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

Solved

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

Mageswari
Shopify Partner
4 0 2

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 += `
<div class="cart-item pb-4" id="CartItem-${item.key}">
<div class="card flex-row flex-wrap gap-4">
<div class="cart-img">
<a href="/products/${item.handle}?variant=${item.variant_id}" class="cart-item__link" aria-hidden="true" tabindex="-1">
<div class="cart-item__image-container gradient global-media-settings">
<img src="${item.image}" class="cart-item__image" alt="${item.title}" loading="lazy" width="170" height="200">
</div>
</a>
</div>
<div class="card-body cart-item__details p-0 position-relative">
<div class="mb-2"><a href="/products/${item.handle}?variant=${item.variant_id}" class="cart-item__name h4 break text-decoration-none">${item.handle }</a></div>
<div class="product-option mb-2">Rs. ${(item.price / 100).toFixed(2)}</div>
<div class="mb-2">
${item.options_with_values.map(option => `
<div class="product-option d-flex flex-wrap gap-2">
<div>${option.name}:</div>
<div>${option.value}</div>
</div>
`).join('')}
</div>
<div class="d-flex mb-2">
<div class="cart-item__quantity border border-2 d-flex justify-content-between align-items-center rounded-pill bg-white">
<button class="decrement-item btn btn-lg" data-line="${item.key}" data-quantity="${item.quantity - 1}">-</button>
<span>${item.quantity}</span>
<button class="increment-item btn btn-lg" data-line="${item.key}" data-quantity="${item.quantity + 1}">+</button>
</div>
</div>
<div class="cart-item__totals mb-2">
<span>Rs. ${(item.line_price / 100).toFixed(2)}</span>
</div>
<button class="cart-remove-button border-0 bg-body position-absolute top-0 end-0" data-line="${item.key}"> <span class="d-none">{{ 'sections.cart.remove' | t }} </span>

</button>

</div>
</div>
</div>
`;
});
}


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));
}

Accepted Solution (1)
BSS-TekLabs
Shopify Partner
2401 695 836

This is an accepted solution.

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.

If our suggestions are useful, please let us know by giving it a like or marking it as a solution.


Salepify: Efficiently increase sales conversion with sale-driven features like auto add to cart, free gifts (free plan available)


Salemate: Boost your AVO with 2-layer offer, countdown upsell in your post purchase page


BSS Commerce - Full-service eCommerce Agency | Use Shopify for 1$ in the first month now

View solution in original post

Replies 4 (4)

BSS-TekLabs
Shopify Partner
2401 695 836
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 += `
                            <div class="cart-item pb-4" id="CartItem-${item.key}">
                                <div class="card flex-row flex-wrap gap-4">
                                    <div class="cart-img">
                                        <a href="/products/${item.handle}?variant=${item.variant_id}" class="cart-item__link" aria-hidden="true" tabindex="-1">
                                            <div class="cart-item__image-container gradient global-media-settings">
                                                <img src="${item.image}" class="cart-item__image" alt="${item.title}" loading="lazy" width="170" height="200">
                                            </div>
                                        </a>
                                    </div>
                                    <div class="card-body cart-item__details p-0 position-relative">
                                        <div class="mb-2">
                                            <a href="/products/${item.handle}?variant=${item.variant_id}" class="cart-item__name h4 break text-decoration-none">
                                                ${item.handle}
                                            </a>
                                        </div>
                                        <div class="product-option mb-2">Rs. ${(item.price / 100).toFixed(2)}</div>
                                        <div class="mb-2">
                                            ${item.options_with_values.map(option => `
                                                <div class="product-option d-flex flex-wrap gap-2">
                                                    <div>${option.name}:</div>
                                                    <div>${option.value}</div>
                                                </div>
                                            `).join('')}
                                        </div>
                                        <div class="d-flex mb-2">
                                            <div class="cart-item__quantity border border-2 d-flex justify-content-between align-items-center rounded-pill bg-white">
                                                <button class="decrement-item btn btn-lg" data-line="${item.key}" data-quantity="${item.quantity - 1}">-</button>
                                                <span>${item.quantity}</span>
                                                <button class="increment-item btn btn-lg" data-line="${item.key}" data-quantity="${item.quantity + 1}">+</button>
                                            </div>
                                        </div>
                                        <div class="cart-item__totals mb-2">
                                            <span>Rs. ${(item.line_price / 100).toFixed(2)}</span>
                                        </div>
                                        <button class="cart-remove-button border-0 bg-body position-absolute top-0 end-0" data-line="${item.key}">
                                            <span class="d-none">{{ 'sections.cart.remove' | t }} </span>
                                        </button>
                                    </div>
                                </div>
                            </div>
                        `;
                    });

                    // 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));
}

If our suggestions are useful, please let us know by giving it a like or marking it as a solution.


Salepify: Efficiently increase sales conversion with sale-driven features like auto add to cart, free gifts (free plan available)


Salemate: Boost your AVO with 2-layer offer, countdown upsell in your post purchase page


BSS Commerce - Full-service eCommerce Agency | Use Shopify for 1$ in the first month now
BSS-TekLabs
Shopify Partner
2401 695 836

This is an accepted solution.

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.

If our suggestions are useful, please let us know by giving it a like or marking it as a solution.


Salepify: Efficiently increase sales conversion with sale-driven features like auto add to cart, free gifts (free plan available)


Salemate: Boost your AVO with 2-layer offer, countdown upsell in your post purchase page


BSS Commerce - Full-service eCommerce Agency | Use Shopify for 1$ in the first month now
Mageswari
Shopify Partner
4 0 2

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

BSS-TekLabs
Shopify Partner
2401 695 836

Glad to help you. Have a good day.

- Please press 'Like' if you find it helpful. Thank you.

If our suggestions are useful, please let us know by giving it a like or marking it as a solution.


Salepify: Efficiently increase sales conversion with sale-driven features like auto add to cart, free gifts (free plan available)


Salemate: Boost your AVO with 2-layer offer, countdown upsell in your post purchase page


BSS Commerce - Full-service eCommerce Agency | Use Shopify for 1$ in the first month now