≡ Menu

In the vast ocean of e-commerce, Shopify stands as a titan, empowering millions of entrepreneurs to bring their dreams to digital life.

While its user-friendly interface makes launching a store seem almost magical, a powerful, often unsung hero works tirelessly behind the scenes: Liquid.

Liquid is Shopify’s open-source templating language, crafted by Shopify’s co-founder Tobias Lütke.

Think of it as the intelligent translator between your store’s data (products, prices, customer info) and the beautiful HTML and CSS that your customers see in their browsers.

It’s the engine that powers your theme, dictating everything from how your product images are displayed to whether a discount message appears for a specific customer.

But what exactly is Liquid, and why should you, a Shopify store owner, care?

Let’s dive in.

The “No-Code” Myth: Why Understanding Liquid is Your Secret Weapon

Many Shopify owners pride themselves on being “no-code” entrepreneurs, and for good reason!

Shopify’s Online Store 2.0 (OS 2.0) themes offer incredible drag-and-drop functionality, allowing you to build stunning storefronts without touching a single line of code.

However, relying solely on pre-built sections and blocks can sometimes feel like trying to paint a masterpiece with only three colors. This is where a basic understanding of Liquid becomes your secret weapon. It allows you to:

  1. Go Beyond Theme Limitations: Want a specific product badge based on inventory levels? A custom message for customers in a particular country? Liquid makes it possible when your theme’s settings fall short.

  2. Optimize Performance: By understanding how Liquid renders content, you can identify and remove unnecessary code, leading to faster load times and improved Core Web Vitals.

  3. Troubleshoot with Confidence: Ever had an app leave behind broken code, or a theme update cause an unexpected glitch? Knowing a little Liquid helps you pinpoint the problem and often fix it yourself, saving you developer fees and downtime.

  4. Communicate Effectively with Developers: If you do hire a developer, being able to articulate your needs in Liquid terms ensures you get exactly what you want, faster and more efficiently.

  5. Future-Proof Your Store: As you scale, your needs become more unique. Liquid provides the flexibility to adapt your store without a complete rebuild.

How Liquid Works: A Glimpse Behind the Curtain

Liquid combines data with templates. Imagine you have a product in your Shopify admin with a title, price, and description. Liquid acts like a merge-field in a document:

  • It identifies specific placeholders (e.g., {{ product.title }}) in your theme files.

  • It fetches the corresponding data from your Shopify store.

  • It injects that data into the HTML, rendering the final output.

This process happens every time a customer loads a page on your store.

The Three Pillars of Liquid: Objects, Tags, and Filters

Liquid is built on three fundamental components:

  1. Objects ({{ ... }}): Objects are the data containers. They hold the information from your Shopify store that you want to display.

    • Example: {{ product.title }} displays the title of the current product.

    • Example: {{ shop.name }} displays your store’s name.

    • Common Objects: product, collection, customer, cart, shop, page, article, blog. Each object has various properties you can access.

  2. Tags ({% ... %}): Tags are the logic and control flow of Liquid. They tell your theme what to do, performing actions like conditionals, loops, and assignments.

    • Control Flow Tags:

      • {% if ... %} / {% else %} / {% endif %}: Used for conditional statements.

        Code snippet:

        {% if product.available %}
          <p>In Stock!</p>
        {% else %}
          <p>Sold Out</p>
        {% endif %}
        
      • {% for ... in ... %} / {% endfor %}: Used to loop through collections of items.

        Code snippet:

        {% for variant in product.variants %}
          <option value="{{ variant.id }}">{{ variant.title }}</option>
        {% endfor %}
        
    • Theme Tags: {% section 'header' %} (includes a section file), {% render 'snippet-name' %} (includes a snippet file).

    • Assignment Tags: {% assign my_variable = 'Hello' %} (creates a temporary variable).

  3. Filters (|): Filters modify the output of an object or variable. They are applied using the pipe (|) character.

    • Example: {{ product.price | money }} displays the product price formatted as currency (e.g., “$29.99”).

    • Example: {{ product.description | truncate: 100 }} shortens the description to 100 characters.

    • Common Filters: date, upcase, downcase, strip_html, plus, minus, times, divided_by, url_encode, img_url. Filters are incredibly powerful for formatting data for display or for use in other parts of your code.

Where Do You Find Liquid in Your Shopify Store?

You’ll encounter Liquid primarily in your theme’s files. To access these, navigate to Online Store > Themes > Actions > Edit code in your Shopify admin.

Key directories where Liquid lives:

  • sections/: Contains modular blocks of content (e.g., header.liquid, footer.liquid, product-template.liquid). OS 2.0 themes are heavily built on sections.

  • snippets/: Smaller, reusable pieces of code that can be included in sections or other templates (e.g., product-card.liquid, icon-svg.liquid).

  • templates/: Core page layouts for different types of content (e.g., product.liquid, collection.liquid, page.liquid, cart.liquid).

  • layout/theme.liquid: The master file that wraps around all other templates, containing global elements like the <html>, <head>, and <body> tags, and often calls for your header and footer sections.

Practical Applications: Small Tweaks, Big Impact

Even without becoming a full-blown developer, a few Liquid tricks can significantly enhance your store:

  • Custom Product Badges: Display “New Arrival” if product.created_at is within the last 30 days, or “Low Stock!” if product.variants.first.inventory_quantity < 5.

  • Conditional Content: Show a special promotion banner only to logged-in customers ({% if customer %}).

  • Dynamic Descriptions: Automatically insert the current year into your copyright notice (Copyright {{ 'now' | date: "%Y" }}).

  • Optimized Image URLs: Use filters like {{ image | img_url: 'medium' }} to ensure images load at appropriate sizes for different devices.

  • A/B Testing with Tags: Assign customers a tag (e.g., test-group-A) and use Liquid to show them different content or pricing.

Embracing the Power of Liquid

In the dynamic world of e-commerce, staying ahead means leveraging every tool at your disposal.

While Shopify makes it easy to get started, understanding Liquid elevates your store from a standard template to a truly bespoke and optimized online presence.

It empowers you to implement subtle yet impactful changes, troubleshoot issues with confidence, and ultimately, create a more engaging and high-performing shopping experience for your customers.

So, don’t shy away from that “Edit code” button.

Start small, experiment, and you’ll quickly discover the immense power that Liquid holds, transforming you from a mere store owner into a true digital artisan.

Useful links below:

Let me & my team build you a money making website/blog for your business https://bit.ly/tnrwebsite_service

Get Bluehost hosting for as little as $1.99/month (save 75%)…https://bit.ly/3C1fZd2

Best email marketing automation solution on the market! http://www.aweber.com/?373860

Build high converting sales funnels with a few simple clicks of your mouse! https://bit.ly/484YV29

Join my Patreon for one-on-one coaching and help with your coding…https://www.patreon.com/c/TyronneRatcliff

Buy me a coffee ☕️https://buymeacoffee.com/tyronneratcliff

{ 0 comments }

Building an e-commerce application is the ultimate “level-up” project for any web developer.

It moves you beyond static pages and into the world of state management, persistent data, and user experience.

In today’s guide, we aren’t just slapping together a list of items; we’re building a scalable architecture.

We’ll start with a clean Vanilla JS frontend and structure our logic so that it’s ready for a professional backend—ideal if you’re planning to scale into a secure environment using a private database.

Whether you’re looking to launch your own side hustle or sharpen your skills for a portfolio, this tutorial will give you the foundational “hooks” you need to go from a blank index.html to a fully functioning shop.

Part 1: Architecture & Data Fetching

In a professional setup, you don’t hardcode products. You fetch them. We’ll use an async function to simulate a call to your future backend.

The “API” Layer

// This will eventually point to your private IP address
const API_URL = "https://api.example.com/products"; 

async function fetchProducts() {
    try {
        // For now, we simulate a network delay
        const response = await fetch('https://fakestoreapi.com/products'); 
        const data = await response.json();
        return data;
    } catch (error) {
        console.error("Database connection failed:", error);
    }
}

Part 2: Building a “Smart” Product Grid

Instead of just showing names, let’s add Category Filtering. Users shouldn’t have to scroll through 100 items to find a mouse.

Updated HTML (Search & Filter)

 

<section class="controls">
    <input type="text" id="search-bar" placeholder="Search products...">
    <select id="category-filter">
        <option value="all">All Categories</option>
        <option value="electronics">Electronics</option>
        <option value="jewelery">Jewelery</option>
    </select>
</section>

The Logic: Filtering and Rendering

let allProducts = []; // Global store for filtering

async function init() {
    allProducts = await fetchProducts();
    renderProducts(allProducts);
}

function renderProducts(productsToDisplay) {
    const grid = document.getElementById('product-grid');
    grid.innerHTML = productsToDisplay.map(product => `
        <div class="product-card">
            <img src="${product.image}" alt="${product.title}" style="width:100px">
            <h3>${product.title}</h3>
            <p class="price">$${product.price}</p>
            <button onclick="addToCart(${product.id})">Add to Cart</button>
        </div>
    `).join('');
}

// Search Event
document.getElementById('search-bar').addEventListener('input', (e) => {
    const filtered = allProducts.filter(p => 
        p.title.toLowerCase().includes(e.target.value.toLowerCase())
    );
    renderProducts(filtered);
});

Part 3: Persistent Shopping Cart (LocalStorage)

The biggest mistake beginners make is losing the cart data when the user refreshes the page.

We solve this using localStorage.

Enhanced Cart Logic:

// Load cart from memory on startup
let cart = JSON.parse(localStorage.getItem('user_cart')) || [];

function addToCart(id) {
    const product = allProducts.find(p => p.id === id);
    
    // Check if item already exists to increment quantity instead of duplicating
    const existingItem = cart.find(item => item.id === id);
    if (existingItem) {
        existingItem.quantity += 1;
    } else {
        cart.push({ ...product, quantity: 1 });
    }
    
    saveAndSync();
}

function saveAndSync() {
    localStorage.setItem('user_cart', JSON.stringify(cart));
    updateCartUI();
}

Part 4: The Checkout Math (Advanced)

A professional cart needs to handle quantities and the dreaded “Remove Item” button. We’ll use the reduce method to calculate totals dynamically.

Professional UI Update:

 

function updateCartUI() {
    const cartContainer = document.getElementById('cart-items');
    
    cartContainer.innerHTML = cart.map(item => `
        <div class="cart-item">
            <span>${item.title} (x${item.quantity})</span>
            <span>$${(item.price * item.quantity).toFixed(2)}</span>
            <button onclick="removeFromCart(${item.id})">×</button>
        </div>
    `).join('');

    const total = cart.reduce((sum, item) => sum + (item.price * item.quantity), 0);
    document.getElementById('cart-total').innerText = total.toFixed(2);
}

function removeFromCart(id) {
    cart = cart.filter(item => item.id !== id);
    saveAndSync();
}

Summary Checklist

Feature Implementation
Data Fetched via async/await from an API.
State Managed in a cart array and synced to localStorage.
UI Built with CSS Grid and dynamic template literals.
UX Includes search, category filtering, and item removal.

Next Steps and Scaling Up

Congratulations!

You now have a working e-commerce engine running entirely on JavaScript, HTML, and CSS.

By implementing localStorage and dynamic rendering, you’ve ensured that your users’ shopping experience is seamless and persistent.

Where do you go from here?

While our frontend is solid, the next big leap is moving your product data from a static file to a live database.

As you begin setting up your production environment—perhaps utilizing that private IP for your database to keep your inventory and customer data secure—you can simply swap out our fetch URLs for your own API endpoints.

Don’t stop here: try adding a “Checkout” button that integrates with Stripe, or implement a “Favorites” list using the same logic we used for the cart.

The sky is the limit when you control the code!

Useful links below:

Let me & my team build you a money making website/blog for your business https://bit.ly/tnrwebsite_service

Get Bluehost hosting for as little as $1.99/month (save 75%)…https://bit.ly/3C1fZd2

Best email marketing automation solution on the market! http://www.aweber.com/?373860

Build high converting sales funnels with a few simple clicks of your mouse! https://bit.ly/484YV29

Join my Patreon for one-on-one coaching and help with your coding…https://www.patreon.com/c/TyronneRatcliff

Buy me a coffee ☕️https://buymeacoffee.com/tyronneratcliff

{ 0 comments }