Skip to content
Tutorials Center
My learning

Topics

Lesson 24 of 28 ยท Projects

Project: A Custom Theme Section

Build an editable FAQ accordion section for a BigCommerce theme: a Handlebars widget template, settings schema, SCSS with CSS variables and accessible JavaScript.

Themes are most useful when merchants can change content without calling a developer. In this project you build one reusable page section, an FAQ accordion, from the pieces you have learned: a Handlebars template, a settings schema the merchant edits in Page Builder, SCSS that follows the theme's design values, and a little JavaScript for behavior and accessibility. Along the way you practice the habit that separates good theme work from copy-and-paste work: every piece has one job and the whole thing works with empty, long and unusual content.

The real pieces (a widget template, its schema, SCSS and JavaScript) need a store and the Stencil tooling, so they are read-only code blocks. Everything runnable is a stand-in in plain JavaScript: a small Handlebars-style renderer that turns the template and some settings into HTML, and the settings and behavior logic extracted into pure functions you can test. They are not the real Handlebars engine, and we say where that matters. Background lessons: Handlebars Templates, Helpers and Page Context, Theme Settings, SCSS and JavaScript and Widgets, Regions and Page Builder.

Why a widget, and not a theme setting

Theme settings in config.json are flat values for the whole theme: a color, a font size, a toggle. They cannot hold a repeating list such as "any number of questions with answers", and they apply everywhere. A widget has its own schema, may contain repeating items, and can be placed in a region of a page by the merchant in Page Builder. So the plan is:

  • The widget template holds the markup and Handlebars logic.
  • The schema describes the editable fields: a heading, a list of question and answer pairs, an accent color and whether only one answer may be open at a time.
  • The theme's SCSS styles the markup and reads colors from CSS variables, so the accent color can change per widget instance.
  • The theme's JavaScript adds the open and close behavior.
flowchart LR
    S["Schema<br/>(what the merchant edits)"] --> T["Widget template<br/>(Handlebars)"]
    T --> H["HTML on the page"]
    C["SCSS<br/>(CSS variables)"] --> H
    J["JavaScript<br/>(toggle, ARIA)"] --> H
    P["Page Builder<br/>(region placement)"] --> S

The merchant edits the schema's fields; the template, styles and script turn them into a working section.

The schema (read-only)

The schema is a JSON array of settings. The exact field types and options are in the current widget documentation, so treat this as a sketch of the shape rather than something to paste in unchecked:

JSON
[
  {
    "type": "tab",
    "label": "Content",
    "sections": [
      {
        "label": "FAQ",
        "settings": [
          { "type": "input", "label": "Heading", "id": "heading", "default": "Frequently asked questions" },
          {
            "type": "array",
            "label": "Questions",
            "id": "items",
            "defaultCount": 2,
            "entryLabel": "Question",
            "schema": [
              { "type": "input", "label": "Question", "id": "question" },
              { "type": "input", "label": "Answer", "id": "answer" }
            ]
          }
        ]
      }
    ]
  },
  {
    "type": "tab",
    "label": "Design",
    "sections": [
      {
        "label": "Appearance",
        "settings": [
          { "type": "color", "label": "Accent color", "id": "accent", "default": "#1a5fb4" },
          { "type": "boolean", "label": "Only one open at a time", "id": "single", "default": true }
        ]
      }
    ]
  }
]

Notice that nothing here is layout. The merchant edits content and a couple of choices; the developer keeps control of structure and accessibility.

The template (read-only)

The widget template receives the merchant's values and produces markup. Each question is a button that controls a panel, linked with aria-controls and aria-expanded, so keyboard and screen reader users get the same experience as mouse users.

HANDLEBARS
<section class="faq" style="--faq-accent: {{accent}};" data-faq data-single="{{single}}">
  {{#if heading}}<h2 class="faq__heading">{{heading}}</h2>{{/if}}
  {{#each items}}
    <div class="faq__item">
      <h3 class="faq__question">
        <button type="button" class="faq__button" aria-expanded="false" aria-controls="faq-panel-{{@index}}" id="faq-button-{{@index}}">
          {{question}}
        </button>
      </h3>
      <div class="faq__panel" id="faq-panel-{{@index}}" role="region" aria-labelledby="faq-button-{{@index}}" hidden>
        <p>{{answer}}</p>
      </div>
    </div>
  {{/each}}
</section>

The double braces escape HTML, so a merchant who types <script> into an answer gets harmless text. Triple braces would output raw HTML and should be reserved for content you trust. The accent color goes into an inline custom property; because it could also be abused (red; background: url(...)), real code should validate colors, which we do in a stand-in below. And an empty items list renders nothing but the heading, which is a state you must test.

Stand-in 1: a mini Handlebars renderer

The real engine runs on the platform when the page is rendered. To see how a template and settings become HTML, this renderer supports just {{name}} (escaped), {{#if name}}, {{#each name}} and {{@index}}. It is far smaller than Handlebars: no helpers, no partials, no else, and it does not nest blocks of the same kind. The code runs in the browser editor.

JS Render the FAQ widget template from settings

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The first output shows two items with consecutive panel IDs from @index, the ampersand in the heading escaped as &amp; and the angle brackets in the question escaped. The empty state renders an empty section, which is valid but useless: in a real section you would hide the whole thing when there is nothing to show ({{#if items}} around the wrapper), and that is exactly the kind of rule this renderer lets you try quickly.

SCSS (read-only)

Styles use a block-element naming scheme (BEM) so they stay local, and read the accent from a CSS variable with a fallback. Spacing and type should come from the theme's existing SCSS variables so the section matches the rest of the store; Cornerstone's variable names differ between versions, so check yours instead of copying names.

SCSS
.faq {
  --faq-accent: #1a5fb4;
  max-width: 48rem;
  margin: 2rem auto;

  &__heading { margin-bottom: 1rem; }

  &__item { border-bottom: 1px solid #d9d9d9; }

  &__button {
    display: flex;
    width: 100%;
    justify-content: space-between;
    padding: 1rem 0;
    background: none;
    border: 0;
    font: inherit;
    text-align: left;
    cursor: pointer;

    &::after { content: "+"; color: var(--faq-accent); font-weight: 700; }
    &[aria-expanded="true"]::after { content: "\2212"; }
    &:focus-visible { outline: 3px solid var(--faq-accent); outline-offset: 2px; }
  }

  &__panel { padding: 0 0 1rem; }
}

The design choices are small but deliberate: a real <button> (not a clickable div), a visible focus style, a plus that becomes a minus using the attribute the script already maintains, and no animation that would ignore users who prefer reduced motion. If you add one, wrap it in @media (prefers-reduced-motion: no-preference).

JavaScript (read-only)

The script finds each section, listens for clicks, flips the aria-expanded state and the hidden attribute, and respects the single-open option. It uses event delegation, so one listener serves the whole section. In a Stencil theme you would load it from the theme's JavaScript bundle (see the page-type classes in Theme Settings, SCSS and JavaScript) or through Script Manager.

JavaScript
document.querySelectorAll('[data-faq]').forEach((root) => {
  const single = root.dataset.single === 'true';
  root.addEventListener('click', (event) => {
    const button = event.target.closest('.faq__button');
    if (!button || !root.contains(button)) return;
    const willOpen = button.getAttribute('aria-expanded') !== 'true';
    if (single) {
      root.querySelectorAll('.faq__button[aria-expanded="true"]').forEach(close);
    }
    willOpen ? open(button) : close(button);
  });
});

function open(button) {
  button.setAttribute('aria-expanded', 'true');
  document.getElementById(button.getAttribute('aria-controls')).hidden = false;
}
function close(button) {
  button.setAttribute('aria-expanded', 'false');
  document.getElementById(button.getAttribute('aria-controls')).hidden = true;
}

Because the panels start hidden in the markup, the page works as a readable list of buttons even before the script loads, and content stays in the HTML for search engines.

Stand-in 2: settings and behavior as pure functions

Two pieces of logic deserve tests without a browser: turning merchant settings into safe CSS values, and deciding which panels are open after a click. Extracting them as pure functions is the same design habit as in Testing Apps and Themes. The code below validates the color, builds the style attribute and simulates clicks in single-open and multi-open modes. This is our own logic mirroring the script above, not the platform's code.

JS Safe CSS variables and the accordion state machine

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Both colors that are not plain six-digit hex values fall back to the default, so the injection attempt never reaches the page. In single-open mode, opening panel 2 closes panel 0, and clicking it a second time closes it again, leaving everything shut; in multi-open mode panels stack up independently. These four states are what a unit test would assert.

Ship it

Before you consider the section done:

  1. Test the states in stencil start: no items, one item, ten items, very long text, text with special characters, and a missing heading.
  2. Check accessibility with the keyboard alone: Tab reaches each button, Enter or Space toggles it, focus is always visible.
  3. Check performance: the section adds no images, no libraries and a few hundred bytes of script, which is the right trade for this feature.
  4. Bundle and push to a sandbox store, add the widget to a region in Page Builder, and edit the content as a merchant would. See Stencil CLI and the Cornerstone Theme.
  5. Document the fields for merchants in a few sentences, and version the change.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why is a widget used for this section instead of theme settings in config.json?

    Theme settings are flat values for the whole theme. A widget has its own schema, can repeat items and is placed per page region.
  2. 2. Why does the template use double braces for the merchant's answers?

    Escaped output prevents merchant-entered or imported text from injecting markup or scripts.
  3. 3. Why is the accent color validated before it is put into a style attribute?

    Any value from a settings field is untrusted input. Validate to an allow-list format and fall back to a default.
  4. 4. What makes the accordion usable with a keyboard and screen readers?

    Native buttons are focusable and respond to Enter and Space, and the ARIA attributes expose the open or closed state.

Summary

  • Use a widget when merchants need to edit repeating content in Page Builder; theme settings are for global values.
  • Keep roles separate: schema for editable fields, template for markup, SCSS for looks, JavaScript for behavior.
  • Escape output, validate setting values used in CSS and design for empty and long content.
  • Build on real buttons and ARIA attributes, keep panels in the HTML and make the page work before JavaScript runs.
  • Extract logic into pure functions so it can be tested without a browser or a store.
  • The runnable renderer is a simplified stand-in; the real Handlebars engine and Page Builder run on the platform.

Next: Project: A Headless Product Page