Snippets

Snippets are reusable pieces of Liquid code that help maintain consistency and reduce duplication across your theme.

Overview

  • Not visible in the theme editor
  • Ideal for code that’s repeated throughout your theme
  • Can be thought of as “components” or “partials”
  • Can be created, deleted, or renamed as needed

Creating Snippets

Snippets are stored in the snippets/ directory with a .liquid extension. For example:
<!-- snippets/course-card.liquid -->
<div class="course-card">
  <img src="{{ course.thumbnail }}" alt="{{ course.name }}">
  <h3>{{ course.name }}</h3>
  <div class="progress-bar">
    <div class="progress" style="width: {{ course.user_data.progress }}%"></div>
  </div>
  <p>{{ course.user_data.progress }}% complete</p>
  <a href="/course/{{ course.id }}" class="button">{{ button_text | default: 'Continue Learning' }}</a>
</div>

Using Snippets

To include a snippet in a section or another snippet, use the render tag:
{% for course_id in all_courses %}
  {% assign course = all_courses[course_id] %}
  {% render 'course-card', course: course, button_text: 'View Course' %}
{% endfor %}

Passing Variables to Snippets

You can pass variables to snippets when rendering them:
{% render 'course-card', 
  course: course,
  button_text: 'Start Learning',
  show_progress: false
%}
Inside the snippet, these variables are available as local variables:
<div class="course-card">
  <h3>{{ course.name }}</h3>
  
  {% if show_progress %}
    <div class="progress-bar">
      <div class="progress" style="width: {{ course.user_data.progress }}%"></div>
    </div>
  {% endif %}
  
  <a href="/course/{{ course.id }}" class="button">{{ button_text }}</a>
</div>

Default Values

You can provide default values for snippet variables using the default filter:
<a href="/course/{{ course.id }}" class="button {{ button_class | default: 'primary-button' }}">
  {{ button_text | default: 'View Course' }}
</a>

Common Snippet Use Cases

UI Components

  • Buttons
  • Cards
  • Navigation elements
  • Progress bars

Content Patterns

  • Course listings
  • Module layouts
  • Lesson previews
  • User information displays

Example: Image Snippet

A snippet for consistently rendering images with optional lazy loading:
<!-- snippets/image.liquid -->
<img
  src="{{ src }}"
  alt="{{ alt | escape }}"
  {% if class %}class="{{ class }}"{% endif %}
  {% if width %}width="{{ width }}"{% endif %}
  {% if height %}height="{{ height }}"{% endif %}
  {% if lazy_load %}loading="lazy"{% endif %}
/>
Usage:
{% render 'image', 
  src: product.image, 
  alt: product.title,
  class: 'rounded shadow',
  width: 300,
  height: 200,
  lazy_load: true 
%}

Best Practices

  • Create snippets for components used in multiple places
  • Pass variables to snippets for flexibility
  • Use consistent naming conventions
  • Keep snippets focused on a single responsibility
  • Document the expected variables for each snippet
  • Use default values for optional parameters