Skip to content
Tutorials Center
My learning

Topics

Lesson 13 of 28 ยท Stencil Themes

Handlebars Templates, Helpers and Page Context

Learn how Stencil themes render pages: Handlebars templates, partials, built-in helpers, page context objects, front matter, and GraphQL in front matter.

A Stencil theme is mostly a set of Handlebars templates. When a shopper opens a product page, BigCommerce picks a template, builds a bag of data about that page (the page context), and renders the template with that data on the server. The result is plain HTML that goes to the browser. If you understand three things, templates, partials and context, you understand most of what a theme developer does all day.

The real Stencil renderer runs on BigCommerce's servers and in the Stencil CLI, so it cannot run here. All theme code in this lesson is shown read-only. The runnable part is our own small Handlebars-style renderer written in Node.js. It supports variables, if, unless, each, with, partials and helpers, so you can see how a template turns data into HTML. It is a teaching stand-in, not the real engine, and the differences are listed at the end.

Where templates live

If you have not seen the theme layout yet, read Stencil CLI and the Cornerstone Theme first. Inside templates/ there are three main folders:

  • templates/layout/ holds page frames, most importantly base.html, which contains the <html>, <head>, header, footer and a slot for the page body.
  • templates/pages/ holds one template per page type: home.html, category.html, product.html, cart.html, page.html and so on. BigCommerce chooses the file from the type of page being requested.
  • templates/components/ holds reusable pieces such as the product card, the header, the breadcrumbs or a form field. Components are included from pages and from each other.

The idea is the same as in any templating system. A page extends a layout and fills its slot, and components keep repeated markup in one place.

flowchart TD
    R["Request: /tote-bag/"] --> T["Pick template<br/>pages/product.html"]
    R --> C["Build page context<br/>(product, settings, customer...)"]
    T --> L["Extend layout/base.html"]
    L --> P["Include components/...<br/>(partials)"]
    C --> P
    P --> H["HTML sent to the browser"]

A request becomes a page type, a template and a context, and the server renders them together.

Templates, layouts and partials

A page template names its layout and provides the content for the layout's slot. In Cornerstone this looks like the following (read-only; the exact slot names are defined by your theme's base.html):

HTML
{{#partial "page"}}
  <main class="page">
    <h1>{{product.title}}</h1>
    {{> components/products/price product=product}}
  </main>
{{/partial}}
{{> layout/base}}

Two Handlebars ideas are at work. {{> path}} includes another template file, a partial, and the path is relative to the templates/ folder, without the .html extension. {{#partial "page"}}...{{/partial}} is a Stencil addition: it defines a named block that the layout then outputs with {{{block "page"}}}. The base layout is therefore rendered last, and it pulls your page content in.

Partials receive the current context by default. You can also pass named values (as in product=product above) when a component should not guess where its data comes from. Prefer passing explicit values for components you reuse in several pages.

Expressions and block helpers

A double-curly expression such as {{product.title}} prints a value and escapes it, so < becomes &lt;. This protects you from injecting markup that a merchant or shopper typed into a field. A triple-curly expression {{{content}}} prints raw HTML. Use it only for values that you know are safe HTML, for example the page body a merchant wrote in the editor or the script block {{{footer.scripts}}}.

Handlebars has a small set of block helpers:

  • {{#if value}}...{{else}}...{{/if}} renders a branch. Empty strings, 0, false, null and empty arrays count as false.
  • {{#unless value}} is the reverse of if.
  • {{#each list}}...{{/each}} repeats a block for every item. Inside it, this is the current item and @index is its position.
  • {{#with object}}...{{/with}} changes the context to object, so you write {{title}} instead of {{product.title}}.

Inside each and with the context changes, and values from the outside are reached with ../, for example {{../product.title}}. Forgetting this is a classic source of empty output.

Stencil helpers

Stencil adds helpers on top of Handlebars. The ones you meet in nearly every theme (read-only examples; check the current helper reference for exact arguments):

HTML
<img src="{{getImage product.image 'product_size'}}" alt="{{product.image.alt}}">
<link rel="stylesheet" href="{{cdn 'assets/css/theme.css'}}">
<p>{{lang 'products.add_to_cart'}}</p>
<span>{{money product.price.without_tax}}</span>
  • lang looks up a translated string from the theme's language files (the next lesson covers them).
  • cdn turns a theme asset path into a CDN URL with a version, so assets are cacheable.
  • getImage builds an image URL for a named size that is defined in config.json.
  • money formats an amount according to the store's currency settings.
  • region marks a place where Page Builder widgets can be added: {{{region name="home_below_menu"}}}. You will use it in Widgets, Regions and Page Builder.
  • inject and jsContext pass values from the server to your JavaScript, which Theme Settings, SCSS and JavaScript uses.

Because the output of helpers goes through the same escaping rules, a helper that returns markup is usually written with triple curlies. When a helper's docs say it returns HTML, follow the docs.

The page context

The context is the data your template can read. Which objects exist depends on the page type, plus a set of objects that are present everywhere. Typical examples:

  • Everywhere: settings (store-level values such as the store name and URLs), theme_settings (values from your theme's config.json and the merchant's customization), customer (the signed-in customer or none), cart basics, urls and page_type.
  • Product page: product with title, price, images, options, reviews and custom fields.
  • Category page: category with its name and description, plus category.products for the listing.
  • Cart page: the items in the cart and totals, usually loaded in the browser.

The best way to see what you actually have is to print it. In a local Stencil session you can add {{json product}} to a template and read the object, or append ?debug=context to a page URL while running stencil start to see the whole context (check the CLI documentation, because debug options can change). Do not rely on a field you have not seen with your own eyes.

Front matter

A page template can start with a block of YAML between --- lines. This front matter tells BigCommerce which extra data to include. For example, a product page can ask for more reviews or videos than the default (read-only):

HTML
---
product:
  videos:
    limit: 8
  reviews:
    limit: 10
---
{{#partial "page"}}
  ...
{{/partial}}
{{> layout/base}}

Front matter keeps the page fast: data is included only when a template asks for it, and the limits are stated next to the markup that uses them.

GraphQL in front matter

A page can also load data with a GraphQL query written in front matter, which gives you fields the default context does not have. The query goes in a gql entry and BigCommerce passes the template's variables, such as the product id, into it (read-only; the available variables and result path are described in the current Stencil documentation):

HTML
---
gql: "query productById($productId: Int!) {
  site {
    product(entityId: $productId) {
      name
      brand { name }
    }
  }
}"
---

The result is added to the context, so the template can read it like any other object. Use this for data that the page does not already provide, and keep queries small, because each one adds work to the render. The Storefront GraphQL API is covered in GraphQL Storefront API.

A Handlebars-style renderer you can run

The stand-in below parses a template into a tree, then renders it with a context. It supports {{path}}, {{{raw}}}, if/unless/else, each with @index, with, ../, partials and simple helpers with arguments. Read the helper functions: they are ordinary JavaScript, which is also how real Handlebars helpers work.

Node.js A tiny Handlebars-style renderer

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

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Look at the output. The & in "Bags & Totes" is escaped as &amp;, the triple-curly line keeps the <b> tag, and the double-curly line shows it as text. The lang helper turned keys into strings, money turned cents into dollars, and ../category.name reached the outer object from inside the loop. The second render prints the loop index too.

Front matter and context together

Real Stencil decides what data to build before it renders. The second stand-in mimics this: it reads simple front matter from a template, builds only the context pieces the page asked for, and then renders. The data source is a fake in-memory store, and the front matter parser handles just the small key: value shape used here.

Node.js Front matter decides what data is loaded

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

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The page asked for two reviews and one video, so the context holds exactly that, while the store has four reviews and three videos. In real Stencil the requested limits live in front matter in the same spirit, though its syntax is richer than this parser.

How the stand-in differs from real Stencil

Be honest about what you ran. The real engine is the Handlebars library with many Stencil helpers added, and it has features the stand-in lacks: sub-expressions such as {{#if (eq a b)}}, hash arguments like name="x", {{#partial}}/{{{block}}} layouts, whitespace control, comments and dozens of helpers. The stand-in also treats every missing value as empty, while the real engine has its own rules for missing data. Use the stand-in to build intuition for scoping, escaping and partials, then read the current helper reference for the helpers you use.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the difference between {{title}} and {{{title}}}?

    Double curly braces escape special characters to protect against injected markup. Use triple braces only for values you know are safe HTML.
  2. 2. Inside {{#each category.products}}, how do you read a value from the outer context?

    each changes the context to the current item. The ../ prefix moves one level back to the parent context.
  3. 3. What is the purpose of front matter in a page template?

    Front matter at the top of a template can request additional data such as more reviews or videos, or load data with a GraphQL query.
  4. 4. Which folder holds reusable pieces such as a product card?

    Components live in templates/components and are included with the {{> path}} partial syntax.

Summary

  • A page request becomes a template from templates/pages/, a layout from templates/layout/, components from templates/components/, and a page context.
  • {{> path}} includes a partial; {{#partial}} and the base layout assemble the page.
  • Double curlies escape; triple curlies print raw HTML and should be rare.
  • if, unless, each and with control flow, and ../ reaches the parent context.
  • Stencil helpers such as lang, cdn, getImage, money and region cover translations, assets, images, prices and widget regions.
  • Front matter requests extra data, and a GraphQL query in front matter can add fields the default context lacks.
  • The runnable renderer is a stand-in for learning, not the real Stencil engine.

Next: Theme Settings, SCSS and JavaScript