Skip to content
Tutorials Center
My learning

Topics

Lesson 14 of 28 ยท Stencil Themes

Theme Settings, SCSS and JavaScript

Learn how a Stencil theme is configured and styled: config.json, schema.json, translations, SCSS settings, the Webpack bundle and page-type JavaScript classes.

Templates decide what a page contains. Three other parts of a theme decide how it looks and behaves: the settings a merchant can change in the theme editor, the styles (SCSS) that turn those settings into CSS, and the JavaScript that makes pages interactive. They are connected. A merchant picks a color in the editor, that value lands in config.json, an SCSS function reads it, and the compiled CSS paints the page.

All of the theme files in this lesson are read-only here, because the Stencil build and the editor live in the CLI and the control panel. The runnable parts are our own stand-ins in JavaScript: a generator that turns settings into CSS custom properties, a small page-class loader and a translation lookup with a fallback language. Each says plainly what is real and what is modelled. If the theme layout is new to you, start with Stencil CLI and the Cornerstone Theme, and for the templates that print these values see Handlebars Templates, Helpers and Page Context.

config.json: defaults and variations

config.json sits in the theme's root. It describes the theme and holds the default value of every setting. A shortened, read-only example:

JSON
{
  "name": "Acme Theme",
  "version": "1.0.0",
  "css_compiler": "scss",
  "template_engine": "handlebars_v4",
  "settings": {
    "color-textBase": "#333333",
    "color-primary": "#1f6feb",
    "product_list_display_mode": "grid",
    "show_product_quick_view": true
  },
  "variations": [
    {
      "name": "Bold",
      "settings": { "color-primary": "#d1242f" }
    }
  ],
  "images": {
    "product_size": { "width": 500, "height": 659 }
  }
}

The settings object is a flat map from a setting id to its default. variations are named presets that override some of those defaults, which merchants see as "styles" they can switch between. The images object defines named image sizes that the getImage helper uses. Other keys control the CSS compiler and the template engine; keep them as they are in the starter theme unless you know why you are changing them.

The final value of a setting is found in layers: the default in settings, then the variation the merchant picked, then the merchant's own edits in the theme editor. Later layers win.

schema.json: the editor controls

A setting that is only in config.json has a default but no control. To let a merchant change it, you describe a control in schema.json. The file is a list of sections, each with a name and a list of controls. Every control has a type, a label and the id of the setting it edits (read-only):

JSON
[
  {
    "name": "Colors",
    "settings": [
      { "type": "heading", "content": "Text" },
      { "type": "color", "label": "Body text", "id": "color-textBase" },
      { "type": "color", "label": "Primary color", "id": "color-primary" }
    ]
  },
  {
    "name": "Products",
    "settings": [
      {
        "type": "select",
        "label": "Product list layout",
        "id": "product_list_display_mode",
        "force_reload": true,
        "options": [
          { "value": "grid", "label": "Grid" },
          { "value": "list", "label": "List" }
        ]
      },
      { "type": "checkbox", "label": "Show quick view", "id": "show_product_quick_view" }
    ]
  }
]

Common control types include heading, paragraph, text, color, checkbox, select and font-style controls. force_reload asks the editor to reload the preview after a change, which you need when the setting changes markup rather than only CSS. Keep ids stable: renaming an id loses the values merchants already saved.

Using settings in templates

In a template, {{theme_settings.color-primary}} prints a value, and {{#if theme_settings.show_product_quick_view}} branches on a checkbox. Setting ids are free-form strings, so keep them consistent (this theme mixes dashes for color ids and underscores for the rest, which is common) and print {{json theme_settings}} while developing to see the exact ids your templates can read.

Translations

Visible words belong in lang/ files, not in templates, so the theme can be translated. lang/en.json holds the default language as a nested object, and other files such as lang/de.json add translations. Templates read strings with the lang helper:

JSON
{
  "products": {
    "add_to_cart": "Add to cart",
    "reviews": "{count} reviews"
  }
}
HTML
<button>{{lang 'products.add_to_cart'}}</button>

The shopper's language decides the file, and when a key is missing the theme falls back to the default language rather than showing nothing. Strings can contain placeholders that you fill when you call lang, and the same files are available to your JavaScript through the context. Keep keys grouped by area (products., cart.) so large themes stay readable.

SCSS: from settings to CSS

Styles live in assets/scss/. The entry file imports partials in a deliberate order: settings and tools first, then base styles, then components. The key idea is that SCSS can read theme settings with special functions that the Stencil build provides. In Cornerstone, variables are defined like this (read-only):

SCSS
$color-textBase: stencilColor("color-textBase");
$color-primary: stencilColor("color-primary");
$product-grid-gap: stencilNumber("product-grid-gap");

.button--primary {
  background-color: $color-primary;
  color: #fff;
}

stencilColor reads a color setting, stencilNumber a numeric one and stencilString a text one; the build also has functions for fonts and images. You never read config.json yourself. The build resolves each call to the final value (default, variation and merchant edits together) when it compiles the theme.

This has a consequence worth remembering: because values are baked into compiled CSS, a changed setting means the CSS must be rebuilt. The editor does this for the merchant, and stencil start does it for you while developing.

flowchart LR
    C["config.json<br/>defaults"] --> M["Merge:<br/>variation + merchant edits"]
    S["schema.json<br/>editor controls"] --> M
    M --> F["stencilColor / stencilNumber<br/>in SCSS"]
    F --> CSS["Compiled CSS"]
    M --> T["theme_settings in templates"]
    M --> J["themeSettings in JavaScript"]

One merged set of setting values feeds the CSS, the templates and the JavaScript.

A settings-to-CSS-variables generator

Modern themes often expose settings as CSS custom properties too, so that small changes need no rebuild. The stand-in below mimics the merge and validation step and writes a :root block. It is our own code: the real build uses SCSS functions, not this generator. It layers defaults, a variation and merchant edits, checks each value against the schema, and rejects bad input such as a color that is not hex.

JS Merge settings and generate CSS variables

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

No output.

The first block prints the default colors. The second shows the Bold variation overriding the primary color, and the merchant's list choice changing a body class. The third lists both problems at once instead of generating broken CSS. In the real system the editor's controls prevent most invalid values; this is why schema.json should describe options exactly.

JavaScript: the Webpack bundle

Theme JavaScript is in assets/js/. The entry file is assets/js/app.js, and Webpack (configured in webpack.conf.js) bundles it with the code under assets/js/theme/. Because each page type needs different behavior, Cornerstone does not run everything everywhere. It loads the class for the current page type, and a global class for code that must run on every page.

The server tells the JavaScript which page it is on by writing a small context object into the page, using the inject and jsContext helpers in base.html (read-only):

HTML
{{inject 'themeSettings' theme_settings}}
{{inject 'productId' product.id}}
<script>window.stencilBootstrap("{{page_type}}", {{jsContext}}).load();</script>

inject registers values and jsContext prints them as JSON. Only inject what the script needs, because everything injected is sent to every visitor in the page HTML.

Page-type classes

A page class extends a shared base class and implements onReady, which runs after the DOM is ready (read-only; names follow Cornerstone and may differ in your theme):

JavaScript
import PageManager from './page-manager';

export default class Product extends PageManager {
  onReady() {
    this.initGallery();
    this.watchOptionChanges();
  }
}

The loader picks Product for product pages, Category for category pages and so on, then calls the shared lifecycle. This keeps the product page's code out of the cart page's bundle chunk and makes the code easy to find: page type in the file name.

The stand-in below models only the dispatching idea: a registry from page type to class, a global class that always runs, and a context with injected values.

JS Load the class for the current page type

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

No output.

You can see that the global class runs first on every page, then the page-specific class runs only where it exists. A page type with no class (the blog here) is not an error; it just gets the global behavior.

Stencil utils and the build

Pages talk to the store through @bigcommerce/stencil-utils, a helper library that wraps the storefront's page and cart requests (for example fetching a product's updated price when an option changes). Use it instead of hand-writing URLs for those calls; check its current README for the functions and callback style, since they are the part of the theme API that changes most. For anything else, your code is ordinary browser JavaScript, so apply normal performance habits: load heavy code only on the pages that need it.

The commands are stencil start for local preview with live reload, stencil bundle to produce the zip and stencil push to upload it. Do not edit files in assets/dist by hand; they are build output and are replaced on every build.

A translation lookup with fallback

Our last stand-in models the lang helper's most important behavior: look in the shopper's language, fall back to the default language, and make a missing key visible instead of blank. Placeholders such as are filled from an object.

JS Translation lookup with fallback

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

No output.

German is used where it exists, English fills the gaps, and a key that exists nowhere shows [missing: cart.nothing], which is easy to spot while testing. The real helper's exact fallback and placeholder syntax are defined by Stencil, so confirm them in the current documentation before relying on details.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Where are the default values of theme settings stored?

    config.json holds the defaults. schema.json describes the editor controls, and variations in config.json override some defaults.
  2. 2. What does stencilColor("color-primary") do in SCSS?

    The Stencil build resolves the call to the merged value of the setting (default, variation and merchant edits).
  3. 3. Why should you inject only the values your script needs with the inject helper?

    Whatever you inject is serialized into the page, so extra data costs bytes and may expose things you did not intend to show.
  4. 4. A merchant's language has no translation for a key. What should a well-built theme do?

    Falling back to the default language keeps the page usable. Missing keys should still be visible during development so they get fixed.
  5. 5. Which file lists the editor controls such as color pickers and selects?

    schema.json describes the sections and controls shown in the theme editor, each tied to a setting id.

Summary

  • config.json holds defaults, variations and image sizes; schema.json describes the editor controls; the final value is default, then variation, then merchant edits.
  • Visible text goes in lang/ files and is read with the lang helper, with a fallback to the default language.
  • SCSS reads settings through functions such as stencilColor, stencilNumber and stencilString, so setting changes need a rebuild.
  • inject and jsContext hand server values to JavaScript; inject sparingly.
  • Webpack bundles assets/js/app.js and the page-type classes under assets/js/theme/; each class extends a base class and implements onReady.
  • stencil start, stencil bundle and stencil push are the daily commands; never edit build output by hand.
  • The generator, loader and translation lookup are stand-ins that model the ideas, not the real build.

Next: Widgets, Regions and Page Builder