Skip to content

Custom charts

When no built-in type draws the shape you need, type: custom lets you draw it yourself. A custom chart is an SVG template: a Jinja-style file that turns the chart's query rows into SVG shapes, rendered by the dbt Charts engine (see The template dialect). The template reads the board's style, so a custom chart picks up the theme's colors and fonts and follows a theme switch like any built-in chart.

Try the built-in types and composed charts first. A built-in chart gets axes, legends, hover, sizing rules, and visual warnings for free; a custom chart draws only what its template draws.

For ready-made templates (Sankey, gauge, radial bar, XmR, isotype, waffle, radar, and globe), see Custom chart examples.


A first custom chart

A template can live inline, under svg:. This one draws a Playfair-style balance chart: two lines with the gap between them filled and labeled, a form no built-in type draws. Its header declares the channels it reads:

charts:
  trade_balance:
    type: custom
    query:
      columns: [year, exports, imports]
      values:
        - [1700, 60, 40]
        - [1710, 75, 50]
        - [1720, 80, 55]
        - [1730, 110, 60]
        - [1740, 125, 80]
        - [1750, 150, 95]
        - [1760, 170, 115]
        - [1770, 200, 130]
    svg: |
      {#---
      description: Two lines with the gap between them filled and labeled.
      channels:
        x:
          description: Column holding the period.
        y:
          description: The upper line's column, then the lower line's.
          multiple: true
      ---#}
      {% set up = channels.y[0] %}{% set lo = channels.y[1] %}
      {% set n = rows | length %}{% set pad = 40 %}
      {% set ymax = [rows | map(attribute=up) | max, rows | map(attribute=lo) | max] | max * 1.1 %}
      {% set x = d3.scale_linear([0, n - 1], [pad, width - pad]) %}
      {% set y = d3.scale_linear([0, ymax], [height - pad, pad]) %}
      {% set ns = namespace(upper=[], lower=[]) %}
      {% for r in rows %}
        {% set ns.upper = ns.upper + [[x(loop.index0), y(r[up])]] %}
        {% set ns.lower = ns.lower + [[x(loop.index0), y(r[lo])]] %}
      {% endfor %}
      <g font-family="{{ style.font.family }}" font-size="{{ style.font.size }}" fill="{{ style.font.color }}">
        <path fill="{{ style.tones.positive }}" fill-opacity="0.3"
          d="{{ d3.line(ns.upper + (ns.lower | reverse | list)) }}Z"/>
        <path fill="none" stroke="{{ style.accent }}" stroke-width="2" d="{{ d3.line(ns.upper) }}"/>
        <path fill="none" stroke="{{ style.fonts.secondary.color }}" stroke-width="2" d="{{ d3.line(ns.lower) }}"/>
        {% for r in rows %}
        <text x="{{ x(loop.index0) }}" y="{{ height - pad / 3 }}"
              text-anchor="middle">{{ r[channels.x] }}</text>
        {% endfor %}
        {% set mid = rows[n // 2] %}
        <text x="{{ x(n // 2) }}" y="{{ y((mid[up] + mid[lo]) / 2) }}"
              text-anchor="middle" dy="0.35em" font-style="italic">Balance in our favor</text>
        <text x="{{ width - pad }}" y="{{ y(rows[n - 1][up]) - 8 }}"
              text-anchor="end" fill="{{ style.accent }}">{{ up }}</text>
        <text x="{{ width - pad }}" y="{{ y(rows[n - 1][lo]) + 22 }}"
              text-anchor="end" fill="{{ style.fonts.secondary.color }}">{{ lo }}</text>
      </g>
    x: year
    y: [exports, imports]
rows:
  - trade_balance
1700 1710 1720 1730 1740 1750 1760 1770 Balance in our favor exports imports Data as of 14:58 UTC on 20 Nov 2026 made withdbt Charts
▶

The template writes SVG content only. dbt Charts draws the title and subtitle, clips the template's output to its drawing box (width x height), and places it on the board.


Template files

Inline templates suit a one-off chart. To reuse a chart across boards, put the template in your project's templates/ folder, next to dbt_charts.yml, and name it with template::

my_project/
├── dbt_charts.yml
├── charts/
│   └── quality.yml
└── templates/
    └── xmr.svg.j2
queries:
  monthly_defects:
    columns: [month, defects_per_k]
    values:
      - [Jan, 41.2]
      - [Feb, 43.0]
      - [Mar, 40.1]
charts:
  defects:
    type: custom
    template: xmr
    query: monthly_defects
    title: Defects per thousand units
    x: month
    y: defects_per_k
rows:
  - defects

template: xmr reads templates/xmr.svg.j2. A chart sets exactly one of template: or svg:.

Finding templates

dct describe reads a template's header, so you never open the file to learn what it takes:

dct describe templates/sankey.svg.j2   # one template
dct describe templates/                # every template in the folder

Each template prints its description, its channels (required or optional, and whether a list is allowed), and its options (type, default, description). dct describe --json returns the same under a template key. Describing a board shows, for each custom chart, the template it uses and that template's description. A template: name with no file lists the templates the project does have, and an unsupported type: such as sankey names the matching template when the project has one.

Channels and options

A template file declares what it takes in a header: a Jinja comment that opens with {#--- and closes with ---#}, holding YAML. It has two parts.

Channels are the chart's data columns, named with the same channel fields built-in charts use: x, y, color, size, shape, theta, and value. A chart sets them at its root, exactly as it would on a bar or pie chart. Pick the channel that matches the role: a period along an XmR chart is x and its measurement is y, the way a line chart reads; a part of a whole is color and theta, the way a pie reads.

Options are everything else the template can be told: a format, a maximum, a symbol. A chart sets them under options:.

{#---
description: XmR process behavior chart, one row per period in time order.
channels:
  x:
    description: Column labeling each period, in time order.
  y:
    description: Column holding each period's measurement.
options:
  value_format:
    type: string
    default: ",.1f"
  run_length:
    type: integer
    default: 8
---#}
type: custom
template: xmr
x: month
y: defects_per_k
options:
  run_length: 6

A channel or option without a default is required; default: null makes it optional with no value, which a template tests with {% if options.target %}. A channel declared with multiple: true takes a list of columns (y: [disease, wounds]) and always reaches the template as a list. A template with no header, an inline one included, takes no channels and no options.

The chart must match the header. A channel or option the header doesn't declare, a missing required one, or a value of the wrong type is a validation error, so a typo fails when the board compiles rather than drawing something wrong. Every channel, and every column option, is also checked against the query's result columns when the chart renders.

Option type Accepts
column The name of a column in the chart's query, for a secondary role such as a gauge's target.
columns A list of column names.
string Any text.
number Any number.
integer A whole number.
boolean true or false.
color A color: hex, a CSS color name, or a palette token.

What a template sees

Name What it holds
rows The query result, one mapping per row: {{ r.revenue }} or {{ r[channels.y] }}. A chart with no query: gets no rows.
columns The result's column names, in order.
channels The columns the chart set for each declared channel: channels.x is a column name, or a list for a multiple channel; an optional channel left unset is none.
options The chart's options, with the header's defaults filled in.
width, height The drawing box in pixels: inside the card padding, below the title. See Where the drawing lands.
uid A prefix unique to this chart. Use it for id values (gradients, clip paths, symbols) so two charts on one board never share an id.
style The board's style, resolved. See Style.
variables The board's variable values for this render: variables.region. A query that reads a variable already returns filtered rows; this is for labels and titles the template draws itself.
math math.sin, math.cos, math.tan, math.asin, math.acos, math.atan2, math.sqrt, math.log, math.exp, math.floor, math.ceil, math.pi, math.tau. Angles are in radians.
d3 d3's scales, ticks, path generators, pie layout, geo projections and geo_path, the same code the built-in charts draw with. See Scales and shapes with d3.

And these helpers:

Helper Returns
value \| format(spec) The value formatted with a d3-format spec, the same formats format: takes elsewhere: {{ 0.432 \| format('.1%') }} gives 43.2%.
value \| format(column=name) The value printed the way a KPI prints that column: the query's formats:, the board's style.formats, and the board's number locale and currency apply. {{ r[channels.y] \| format(column=channels.y) }} follows the column, and the same call formats a number the template derives, such as a total. A column the query did not return is an error that lists the ones it did. A spec and column= together is an error. Numbers only: column= on a date or text value is an error, so print those as the query returned them ({{ r.date }}). With no rows the query returned no columns, so column= is an error there too: guard a derived total with {% if rows %}.
text_width(text, size, weight) The width in pixels of text, a string, in the board's font at size pixels: text_width(r.name, style.font.size). Turn a number into text first, with \| string or \| format(...). weight is optional and defaults to 400. It takes any weight style can carry: a whole number from 1 to 1000 such as 600, or a CSS keyword such as bold or normal, so style.charts.title.font.weight works whatever the theme sets. Digits measure as tabular (equal-width) numerals, the way the engine draws axis numerals, so a margin sized from text_width('100', size) fits the axis labels the board draws beside it. Use it to fit or wrap labels.
color_for(value, column) The board's pinned color for that column and value, from style.charts.category_colors, so a pinned category matches the built-in charts on the board. A value with no pin gets the next color of the categorical palette, in the order the template asks; the same value always gets the same color within a chart, and running out of palette colors is an error.
label_ink(color) color as text ink on the chart's own background: the dark step the built-in charts paint direct labels in, held to a 4.5:1 contrast floor. It works on light and dark themes alike: fill="{{ label_ink(color_for(r.name)) }}". color is a hex color.
variant(color, kind) A literal tier of color, the same math as a categorical palette variant: kind is light, dark, pale, or deep. variant(color_for(r.name), 'pale') is a quiet fill behind a mark. color is a hex color.
href(row) The chart's link: for that row, with every {{ name }} placeholder filled from the row: a channel reads the column it binds, any other name the row's column of that name. See Links.
raise_error(message) Stops the render and shows message in the chart's place. Use it to reject data the template cannot draw.

Templates use strict variables: a misspelled column, option, or style key is an error that names the template and line, not an empty string.

Write a negative angle as -1 * math.pi / 2 or -(math.pi) / 2: the engine reads -math.pi as the negation of math.

Query values arrive as the warehouse returns them. Some warehouses return decimals, so convert before doing arithmetic with floats: {{ (r.revenue | float) * scale }}.


Scales and shapes with d3

d3 holds d3's scales, tick ladders and path generators, so a template maps data to pixels and draws curves and arcs with the numbers the built-in charts use instead of rebuilding them in Jinja. Names follow d3 in snake_case. Every function takes its arguments by position or by keyword, and a bad argument (a zero-width domain, a non-numeric value, an unknown curve) fails the chart with an error naming the call, such as d3.scale_linear(): domain must not be zero-width.

Function Returns
d3.scale_linear(domain, range) A scale for two-number lists: x(value) maps a domain value to the range, x.invert(pixel) maps back, and x.domain and x.range read the ends. x.nice(count=10) returns a new scale whose domain ends on round ticks. x.ticks(count=10) lists the ticks. x.tick_format(count=10, spec=none) returns a function that prints a value with the precision the ticks need, through the board's number locale; spec is a d3-format spec such as '$,s' or '%'.
d3.scale_sqrt(domain, range) The same, with the range proportional to the square root of the value: a circle's radius, so that its area follows the value. nice, ticks and tick_format work on the domain.
d3.scale_log(domain, range, base=10) The same over a domain that does not cross or touch zero (a negative domain mirrors, as in d3). x.ticks(count=10) lists every multiple of each power of the base when the domain spans few powers, else the powers. x.nice() rounds the ends to powers of the base. x.tick_format(count=10, spec=none) prints through spec ('s' for base 10, else ',', zeros trimmed when it sets no precision) and prints "" for the ticks d3 thins from a crowded decade. A value with no position on the scale, such as 0, is an error.
d3.scale_pow(domain, range, exponent=1) The same, with the range proportional to the value raised to exponent, which is not zero.
d3.scale_symlog(domain, range, constant=1) The same through a symmetric log, which reaches zero and negative values; constant is positive.
d3.scale_band(domain, range, padding=0, padding_inner=0, padding_outer=0, align=0.5) A scale from a list of distinct names to evenly spaced bands: b(name) is the band's start, b.bandwidth() its width and b.step() the distance between starts. padding= sets both paddings, as in d3. A name outside the domain is an error. A repeated domain value keeps its first position.
d3.scale_point(domain, range, padding=0, align=0.5) A band scale of zero width: p(name) is the point's position and p.step() the distance between points. padding= is the outer padding, as in d3; a single point sits at the center of the range. A name outside the domain is an error.
d3.line(points, curve="linear") The d of a path through points, a list of [x, y] pairs. An empty list gives an empty path.
d3.area(points, y0, curve="linear") The d of a closed path filling between the curve through points and the horizontal line at y0.
d3.arc(inner_radius, outer_radius, start_angle, end_angle, pad_angle=0, corner_radius=0) The d of an annular sector centered on the origin. Angles are in radians, clockwise from twelve o'clock; place it with transform="translate(cx, cy)".
d3.pie(values, start_angle=0, end_angle=math.tau, pad_angle=0) One mapping per value, index, value, start_angle, end_angle and pad_angle, ready for d3.arc. Slices follow the order of values, not d3's default of largest first: sort in the query. A negative value is an error.
d3.geo_mercator(), d3.geo_equal_earth(), d3.geo_orthographic(), … A d3-geo projection: p([lon, lat]) is the planar point (none where the projection has no place for it) and p.invert([x, y]) maps back. Each d3 setting is a method that reads with no argument and, with one, returns a new projection: scale, translate, center, rotate ([lambda, phi] or [lambda, phi, gamma], degrees), parallels (conic projections), clip_angle (none for the antimeridian), clip_extent ([[x0, y0], [x1, y1]] or none), precision, angle, reflect_x, reflect_y. fit_extent(extent, object), fit_size([width, height], object), fit_width(width, object) and fit_height(height, object) return a projection scaled and translated to show the GeoJSON object in that box. The projections are geo_albers, geo_albers_usa, geo_azimuthal_equal_area, geo_azimuthal_equidistant, geo_conic_conformal, geo_conic_equal_area, geo_conic_equidistant, geo_equal_earth, geo_equirectangular, geo_gnomonic, geo_identity, geo_mercator, geo_mollweide, geo_natural_earth1, geo_orthographic, geo_stereographic and geo_transverse_mercator; geo_identity is planar and has only scale, translate, clip_extent, angle and the reflections, and geo_albers_usa only scale, translate and precision.
d3.sankey(links, nodes=none, size=none, extent=none, node_width=24, node_padding=8, align="justify", iterations=6) d3-sankey's layout. links is a list of {source, target, value} mappings naming nodes by string or number; the nodes are those names in order of first appearance, or nodes, a list that fixes their order. size=[width, height] or extent=[[x0, y0], [x1, y1]] is the box (d3's unit square by default); align is justify, left, right or center. Returns {nodes, links}: each node {name, index, value, depth, height, layer, x0, x1, y0, y1, source_links, target_links} (the link lists hold indices into links), each link {index, source, target, value, width, y0, y1} with source and target the node mappings. A cycle is an error.
d3.sankey_link_horizontal(link) d3-sankey's sankeyLinkHorizontal: the d of a link's centerline from its source node to its target node; stroke it with stroke-width="{{ link.width }}" and fill="none". Printed the way the engine prints every chart's path (two decimals at most).
d3.stack(series, order="none", offset="none") d3-shape's stack(). series is a list of lists of numbers, series[i][j] the value of series i at point j (none for no datum); every list needs the same length. Returns {series, index}: series[i][j] is [y0, y1] (none where there is no datum; a datum whose span overflows is an error) and index[i] is series i's place in the stacking order. order is none, ascending, descending, inside_out, reverse or appearance; offset is none, expand, diverging, silhouette or wiggle.
d3.symbol(type="circle", size=64) d3-shape's symbol: the d of a shape of size square pixels centered on the origin. Filled types: circle, cross, diamond, square, star, triangle, wye; stroked (1.5px, round caps): plus, times, triangle2, asterisk, square2, diamond2. Printed the way the engine prints every chart's path (two decimals at most).
d3.format(spec) A function printing a number with a d3-format spec through the board's number locale, the format filter as a value to pass around: {% set money = d3.format('$,.0f') %}.
d3.scale_utc(domain, range) d3's scaleUtc for two instants (epoch milliseconds or ISO-8601 text, a bare clock read as UTC) and a two-number range: x(instant) maps an instant to the range, x.invert(pixel) maps back to milliseconds, and x.domain (milliseconds) and x.range read the ends. x.ticks(count=10) lists the tick instants in milliseconds, on the UTC calendar boundaries d3 picks; x.nice(count=10) returns a new scale whose domain ends on them. x.tick_format(count=10, spec=none) returns a function printing an instant in UTC through the board's time locale: with no spec, d3's multi-scale format (.089, :07, 09:05, 09 AM, Tue 12, Mar 10, March, 2024); otherwise a d3-time-format spec such as '%b %d'.
d3.time_format(spec), d3.time_parse(spec) d3-time-format's utcFormat and utcParse through the board's time locale (its month, weekday and AM/PM names). d3.time_format('%b %d, %Y')(instant) prints an instant (milliseconds or ISO-8601 text) in UTC; d3.time_parse('%d.%m.%Y')(text) returns the instant in milliseconds, or none when the text does not fit the spec or names no date.
d3.interpolate_rgb(a, b), d3.interpolate_hcl(a, b) A function of t from 0 to 1 mixing two colors (hex, rgb(), hsl() or a CSS name) in sRGB or in HCL, printed as d3 prints it, rgb(r, g, b).
d3.scheme_category10, d3.scheme_accent, d3.scheme_dark2, d3.scheme_paired, d3.scheme_pastel1, d3.scheme_pastel2, d3.scheme_set1, d3.scheme_set2, d3.scheme_set3 d3-scale-chromatic's categorical schemes as lists of hex colors. For colors that follow the board's theme use style.charts.color.categorical.palette or color_for instead.
d3.geo_path(projection=none, digits=3, point_radius=4.5) d3's geoPath: path(object) is the d of a GeoJSON object through projection (planar coordinates as they are when none), or none when nothing is drawn, such as a point on the far side of a globe. path.area(object), path.bounds(object), path.centroid(object) and path.measure(object) are the drawn shape's planar area, [[x0, y0], [x1, y1]], centroid and perimeter. digits rounds the coordinates as d3 does (none for unrounded) before the engine prints the path the way it prints every chart's, to at most two decimals, and point_radius sizes the circle a point draws as.

Curves are linear, monotone_x, monotone_y, step, step_before, step_after, basis, natural and cardinal.

A GeoJSON object is a Feature, FeatureCollection or geometry mapping ({"type": "Point", "coordinates": [lon, lat]}, {"type": "Sphere"} for the whole globe) or its JSON text, such as a column a warehouse's ST_AsGeoJSON returns. The globe template draws one from rows of longitude and latitude.

A scale and its ticks replace the arithmetic a template would otherwise repeat. This one draws a bar chart with a gridline and label at every tick:

{% set bars = d3.scale_band(rows | map(attribute=channels.x) | list, [0, width - 40], padding=0.2) %}
{% set value = d3.scale_linear([0, rows | map(attribute=channels.y) | max], [height - 20, 14]).nice() %}
{% set label = value.tick_format() %}
{% for tick in value.ticks() %}
  <line x1="0" x2="{{ width - 40 }}" y1="{{ value(tick) }}" y2="{{ value(tick) }}"
        stroke="{{ style.charts.axis.grid.color }}"/>
  <text x="{{ width - 36 }}" y="{{ value(tick) }}" dy="0.35em"
        fill="{{ style.fonts.secondary.color }}">{{ label(tick) }}</text>
{% endfor %}
{% for r in rows %}
  <rect x="{{ bars(r[channels.x]) }}" y="{{ value(r[channels.y]) }}"
        width="{{ bars.bandwidth() }}" height="{{ value(0) - value(r[channels.y]) }}"
        fill="{{ style.charts.color.categorical.single_series_palette[0] }}"/>
{% endfor %}

Style

style has the same structure as the style: block you author on a board or in a theme, after the theme, the board's style:, and every inherited value are merged. So a key you can set is a key a template can read, at the same path:

In a template What it is
style.background The board background.
style.font.family, style.font.color, style.font.size Body text.
style.fonts.secondary.color, style.accent Secondary text and the accent color.
style.tones.positive, .negative, .warning, .info Status colors.
style.charts.color.categorical.palette The categorical palette built-in charts use, as a list of colors.
style.charts.color.categorical.single_series_palette[0] The color of a single-series chart.
style.charts.axis.grid.color Gridlines and tracks.
style.charts.axis.labels.font Axis label text.
style.charts.title.font Chart title text.
style.palettes.<role> Each palette role, resolved: a list of colors for a categorical, sequential, or diverging palette, and a mapping of named stops (solid, bg, border, text, ...) for a tone.
style.palettes.chrome[n] The neutral scaffold: the list of gray stops the built-in charts draw axes, rules, and backgrounds from, so a template's chrome follows the theme. Index from 0.

Every color is a resolved hex value. The one difference from what you author is palettes:: you name a palette (category: editorial-10), and the template sees its colors.

Read colors and fonts from style rather than writing them into the template, and the chart follows every theme, dark ones included, without changes. The examples never hard-code a color.

To pin a category's color across every chart on a board, built-in or custom, use style.charts.category_colors and read it in the template with color_for(value, column):

style:
  charts:
    category_colors:
      qualification:
        values:
          Graduates: "#2b59a8"
          Certificated: "#d33a32"

A custom chart takes link: like every other chart. A link with no placeholder wraps the whole drawing in one anchor, so the chart is clickable with no change to the template:

type: custom
template: xmr
link: /boards/quality

A link with placeholders is per row: link: /boards/month/{{ x }} fills {{ x }} from the column the x channel binds (any other name, such as {{ month_id }}, from that column of the row), and the template decides which marks carry it by wrapping them in an anchor:

{% for r in rows %}
<a href="{{ href(r) }}"><rect .../></a>
{% endfor %}

A per-row link is drawn only where the template calls href, so a template that never calls it with such a link fails the chart rather than quietly dropping the link. A board path resolves against the host like any chart link; http, https and mailto URLs pass through; any other scheme is refused.


Fonts

style.font.family is the board's font stack, and style.charts.title.font, style.charts.axis.labels.font and the other font blocks carry the family, size, weight and color the built-in charts use. A template that writes font-family="{{ style.font.family }}" paints the board font, and an export embeds that font the way it does for every other chart. text_width measures in the same font, at the weight you pass it.


Where the drawing lands

The engine draws the title and subtitle, then places the template's output in a group translated below them, inside the card's padding. width and height are that box, so a template draws from (0, 0) to (width, height) and never allows for the title or the padding itself. Anything drawn outside that box is clipped, so it cannot paint over the title. A chart with no title: hands the template the full card height.


What a template may draw

A template's output must be well-formed SVG built from drawing elements: shapes (rect, circle, ellipse, line, polyline, polygon, path), text (text, tspan, textPath), grouping (g, defs, symbol, use), paint (linearGradient, radialGradient, stop, pattern, clipPath, mask, marker), title and desc, and a with an href the link rules accept.

The output is checked before it reaches the board, and anything outside that set is an error that names the element or attribute. Nothing is silently removed. Not allowed:

  • <script>, <foreignObject>, <style>, <image>, and animation elements such as <animate> and <set>
  • filters (shadow, blur) and raster images: neither fits the sandboxed, vector-only output, so <filter> is refused along with <image>
  • event attributes such as onclick
  • the board's own hooks: role, aria-* and data-* attributes, and class names starting with role- or dbt-, which the page's runtimes read
  • a paint attribute (fill, stroke, stop-color, ...) that is not a color, none, currentColor or url(#id)
  • elements nested more than 64 levels deep
  • references out of the page: outside <a>, href must be a #id reference (href="#{{ uid }}-person"), and url(...) must be url(#id) (fill="url(#{{ uid }}-fade)")
  • comments, processing instructions, and CDATA sections
  • CSS escapes (a backslash in an attribute) and CSS functions other than url(#id) that load a resource, such as image-set()

Values written with {{ }} are escaped, so a label containing < or & draws as text.

A <title> inside a shape becomes the browser's native tooltip: delayed, unstyled, and absent on touch and in PNG or PDF exports. It is not the board's tooltip card.


The template dialect

The engine renders templates with minijinja, a Jinja implementation with no reflection into the host, so a template can reach only the names listed above. Blocks, loops, macros, namespace(), dict() with ** merging, and the common filters all work as in Jinja. The difference is that values have filters, not Python methods:

Instead of Write
text.split(",") text \| split(",")
d.get(k, 0) d[k] if k in d else 0
d.keys(), d.values() d \| items \| map(attribute=0), ... \| map(attribute=1)
x \| round(0, "ceil") math.ceil(x)
"%d" % n n \| format('d')

A syntax the engine does not accept fails when the board compiles, naming the line. Two budgets bound a template, and crossing either fails the chart, never the board: a runaway loop ends on an instruction budget, and the output is capped by the project's execution.max_template_output_bytes.


Writing good templates

Let the query do the math. Jinja is good at loops and text, and slow and awkward at algorithms. Sorting, ranking, running totals, shares, and binning belong in SQL. The XmR example computes its limits in the template only because they are a few sums; a layout that needs iteration is a sign the shape should be a built-in type.

Validate the data. Check what the template depends on and stop with raise_error when it is wrong: a gauge with more than one row, a Sankey whose flows loop back, a negative value in a waffle.

Use uid for every id. A board renders many charts into one document, so an id like fade would collide when a template is used twice.

Leave room for text. Measure labels with text_width instead of guessing, and keep a fixed margin for labels that sit outside the marks.


Errors

Code When
ERR-CUSTOM-TEMPLATE The template file is missing, its header is not valid YAML, or the template has a syntax error.
ERR-CUSTOM-FIELDS A channel or option the header doesn't declare, a missing required one, or a value of the wrong type.
ERR-CUSTOM-RENDER The template failed while drawing: a missing column, an undefined name, or a raise_error call.
ERR-CUSTOM-SVG The output is not well-formed SVG, or uses an element or attribute that is not allowed.