Skip to main content

Template Hooks

Hook Lifecycle Flow

1. Section Initialization Phase

  • onSectionInit is called when section is first created
    • Sets up initial state and variables
    • Configures section parameters
    • Registers event listeners

2. Data Fetching Phase

  • getProductDetailsQuery is called to prepare GraphQL query
    • Defines required product fields
    • Sets up query variables
    • Configures custom data requirements
    • Sets up filtering parameters

3. Data Processing Phase

  • postProductFetch processes raw product data
    • Filters products if needed
    • Adds computed properties
    • Transforms data structure
  • transformProductData transforms individual product data
    • Normalizes data format
    • Adds custom fields
    • Prepares for rendering

4. Rendering Phase

  • afterSectionRendered is called once section is rendered on the page and ready to be used. Note: This is an optional hook, if you want to perform certain task, you can add your logic in this hook.
  • initSwiper (if carousel is enabled)
    • Configures carousel settings
    • Sets up navigation
    • Initializes responsive behavior
    • Sets up pagination

5. Interaction Phase

  • onVariantChange handles variant selection Note: This is an optional hook, if you want to perform certain task, you can add your logic in this hook.
  • onSwatchChange handles swatch interactions Note: This is an optional hook, if you want to perform certain task, you can add your logic in this hook.

6. Cart Operation Phase

  • beforeAddToCart validates cart operations
    • Validates product selection
    • Modifies cart payload
    • Handles quantity validation
  • afterAddToCart handles post-cart updates Note: This is an optional hook, if you want to perform custom logic, you can setup your logic in this hook.

Available Hooks

1. onSectionInit

Purpose:
Primary initialization hook called when a section is first created.
Parameters:
  1. args contains:
    • recommendation object which includes:
      • section containing section ID, layout type, title, and discount configuration
      • Array of products with product data
    • engine object containing:
      • Engine name and version
      • Engine-specific configuration
    • initEnginePayload containing engine initialization data
  2. cb (Callback Function):
    • Receives the processed recommendation object
    • Used to handle initialization completion
    • No return value expected
  3. gloodUtils provides:
Example:
Use Cases:
  • Section configuration
  • State initialization
  • Event listener setup
  • Feature initialization
  • Engine configuration

2. getProductDetailsQuery

Purpose:
Builds the GraphQL query for fetching product data.
Parameters:
  1. recommendation contains:
    • section object with:
      • id (number): Unique section identifier
      • layout (String): Section layout type
      • discount_config (Object): Discount settings
      • widget_message (String): Custom message template
    • products (Array): Currently loaded products
    • template (Object): Template-specific settings
  2. glood provides:
    • shop object containing:
      • money_format (String): Store currency format
      • locale (String): Store language code
    • product object with:
      • id (String): Current product context (format: “gid://shopify/Product/”)
      • handle (String): Product URL handle
    • localization settings for:
      • Currency formatting
      • Language preferences
      • Regional settings
Returns:
GraphQL query string containing required product fields
Example:
Use Cases:
  • Product data fetching
  • Field selection
  • Query customization
  • Data filtering
  • Performance optimization

3. postProductFetch

Description:
Processes raw product data after fetching. Allows for data transformation and enrichment before rendering.
Parameters:
  • args (Object):
    • products (Array): Raw product data array
    • recommendation (Object): Section configuration
    • template (Object): Template settings
  • utils (Object): Helper functions
Returns:
Array - Processed product data
Example:
Use Cases:
  • Price formatting
  • Discount calculations
  • Image optimization
  • Availability checks
  • Data enrichment

4. transformProductData

Purpose:
Transforms raw GraphQL product data into template-friendly format.
Parameters:
  1. product (Raw GraphQL data) contains:
    • Basic information:
      • id (String): GraphQL product ID (format: “gid://shopify/Product/”)
      • handle (String): Product URL handle
      • title (String): Product title
      • vendor (String): Product vendor
    • Images:
      • featuredImage (Object): Main product image
      • images (Object): Additional product images
    • Pricing:
      • priceRange (Object): Min/max prices
      • compareAtPriceRange (Object): Original prices
    • Variants:
      • variants (Object): Product variants data
      • variantsCount (Object): Total variants count
    • Options:
      • options (Array): Product options
      • selectedOptions (Array): Default selections
    • Status:
      • availableForSale (Boolean): Stock status
      • tags (Array): Product tags
  2. recommendation provides:
    • section settings:
      • Display configuration
      • Pricing rules
      • Layout settings
      • Tracking configuration
Returns:
Product object containing:
  • Normalized product data
  • Formatted prices
  • Processed images
  • Structured variants
  • Computed fields
Example:
Use Cases:
  • Tracking setup
  • Variant processing
  • Label generation
  • Price formatting
  • Custom field addition

5. initSwiper

Purpose:
Initializes and configures the carousel/slider functionality for sections using Swiper.js.
Parameters:
  1. Swiper (Constructor Class):
    • Swiper.js constructor
    • Used to create carousel instances
    • Handles slide functionality
    • Manages touch events
    • Controls navigation
  2. templateSettings contains:
    • template.settings with:
      • carousel (Object): Carousel-specific settings
      • breakpoints (Object): Responsive configuration:
        • small (Object): Mobile settings
        • medium (Object): Tablet settings
        • large (Object): Desktop settings
      • Each breakpoint contains:
        • screenSize (Number): Width breakpoint
        • cardsPerView (Number): Visible slides
        • gutter (Number): Space between slides
  3. container (HTMLElement):
    • Root section element
    • Contains carousel structure:
      • Wrapper element
      • Slide elements
      • Navigation buttons
      • Pagination dots
  4. params contains:
    • recommendation:
      • section (Object): Section configuration
      • products (Array): Product data
      • Layout settings
    • Template-specific parameters
  5. defaultSettings contains:
    • Default Swiper configuration:
      • Navigation options
      • Pagination settings
      • Autoplay configuration
      • Effect settings
      • Loop behavior
  6. utils provides:
    • merge: Deep object merging
    • DOM manipulation helpers
    • Event handling utilities
    • Error handling functions
Returns:
  • Swiper instance if initialization succeeds
  • undefined if initialization fails
Example:

6. onVariantChange

Purpose:
Handles product variant selection changes and updates the UI.
Parameters:
  1. args contains:
    • variant information:
      • Basic details: ID, price, compare price
      • Image information with source and alt text
      • Availability status and quantity
      • Selected options (color, size, etc.)
    • Complete product data
    • DOM container element for the product card
  2. utils provides:
    • Price formatting functions
    • Image update utilities
    • Price display update functions
    • Other UI manipulation helpers

7. onSwatchChange

Purpose:
Handles swatch selection events and updates product display accordingly.
Parameters:
  1. args contains:
    • option object with:
      • name (String): Option name (e.g., “Color”, “Size”)
      • value (String): Selected option value
      • type (String): Swatch type (color/size/material)
      • swatchImage (String, optional): Custom swatch image URL
    • product object containing:
      • variants (Array): All product variants
      • options (Array): Available option types
      • selectedVariant (Object): Currently selected variant
      • images (Array): Product images
    • container (HTMLElement): Product card DOM element
  2. utils provides:
    • updateSwatchUI: Updates swatch selection state
    • findMatchingVariant: Finds variant by options
    • updateProductImage: Updates product image
    • updatePriceDisplay: Updates price display
    • Event tracking utilities
Returns:
void

8. onCartOperationComplete

Purpose:
Handles post-cart operation tasks and updates UI accordingly.
Parameters:
  1. args contains:
    • operation (String): Type of operation (‘add’|‘update’|‘remove’)
    • response object with:
      • cart (Object): Updated cart state
      • items (Array): Modified cart items
      • total (Number): New cart total
      • count (Number): Updated item count
    • section containing:
      • Section configuration
      • Template settings
      • Tracking data
    • container (HTMLElement): Section container
  2. utils provides:
    • updateCartUI: Updates cart display
    • showNotification: Displays notifications
    • updateInventory: Updates stock status
    • Animation utilities
  3. gloodUtils provides:
    • trackCartEvent: Analytics tracking
    • formatCartData: Data formatting
    • updateShopifyCart: Cart sync utilities
    • Store-specific helpers
Returns:
void

9. validateCartOperation

Purpose:
Validates and potentially modifies cart operations before execution.
Parameters:
  1. payload contains:
    • Array of items being added/modified:
      • Product identifier
      • Variant identifier
      • Quantity
    • Additional cart-specific data
  2. recommendation provides:
    • section configuration
    • Product data
    • Template settings
  3. utils and gloodUtils:
    • Validation helpers
    • Cart operation utilities
    • Format and transformation functions
Returns:
  • Modified payload if valid
  • Error message if validation fails
  • Optional redirect URL

10. onProductDataReceived

Purpose:
Processes raw product data before transformation and rendering.
Parameters:
  1. args contains:
    • products array with raw product data:
      • id (number): Product identifier
      • title (String): Product title
      • handle (String): Product URL handle
      • featuredImage (Object): Main product image
      • variants (Array): Raw variant data
      • options (Array): Product options
      • tags (Array): Product tags
    • section object with:
      • Layout configuration
      • Discount settings
      • Template rules
      • Display settings
    • template containing:
      • Breakpoint settings
      • Card configuration
      • Image dimensions
      • Price display rules
  2. utils provides:
    • processImages: Image optimization utilities
    • formatProductData: Data formatting helpers
    • validateProducts: Data validation functions
    • enrichProductData: Data enrichment utilities
    • handleErrors: Error handling functions
Returns:
void

11. loadAjaxCart

Purpose:
Determines when to load the AJAX cart section by checking if the AJAX cart is active.
Parameters:
  1. bodyElem (HTMLElement):
    • The document body element
    • Provides access to AJAX cart state
Returns:
Boolean - True if AJAX cart is active and should be loaded
Example:
Use Cases:
  • Update recommendations dynamically when products are added to cart

12. unloadAjaxCart

Purpose:
Determines when to unload the AJAX cart section by checking if the AJAX cart is inactive.
Parameters:
  1. bodyElem (HTMLElement):
    • The document body element
    • Provides access to AJAX cart state
Returns:
Boolean - True if AJAX cart is inactive and should be unloaded
Example:
Use Cases:
  • Control AJAX cart unloading timing
  • Clean up cart resources
  • Manage AJAX cart states
  • Handle cart closure events

Hook Dependencies

Required Utils

  • formatMoney: Price formatting
  • getVariantById: Variant lookup
  • updateUrl: URL manipulation
  • merge: Object merging
  • imageOptimizer: Image optimization

Global Context

  • glood: Store configuration
  • translations: Text strings
  • template: Template settings
  • section: Section configuration
  • utils: Common utilities

Hook Flow Dependencies

  • transformProductData needs data from getProductDetailsQuery
  • afterSectionRendered needs data from transformProductData
  • Cart operations need data from onVariantChange
  • Swiper needs container from afterSectionRendered

Error Handling

Each hook should handle these critical errors:
  1. Carousel Initialization Errors
  2. Product Data Transformation Errors
  3. GraphQL Query Response Errors
These errors require immediate attention as they:
  • Prevent sections from rendering correctly
  • Break core product functionality
  • Impact the shopping experience
  • Can cause JavaScript runtime errors

Support

If you need help with creating or customizing section templates, contact our support team at support@glood.ai