Expressions & formats

Expressions compute values; formats decide how those values look.

Expressions

Expressions appear in <t-out expr="…">, <t-let expr="…"> and \val{…} inside formulas. They're ordinary JavaScript expressions. A name in an expression is one of three things:

  1. A function you registered with registerFunction.
  2. A standard JavaScript global from a short list: Math, Number, String, Boolean, Array, Object, JSON, Date, Intl, parseInt, parseFloat, isNaN, isFinite, Infinity, NaN and undefined.
  3. A variable: every other name, whether or not it has been declared yet.

There are no other names, so Math is spelled out (Math.sqrt(x), Math.PI), and nothing else from window leaks in: a variable called top, name or length is simply a variable. If a variable and a registered function share a name, the variable wins once it has a value.

A circle with radius 1.5 has an area of and a circumference of . Rounded up, that's a -unit-wide box.

Your own functions

For anything longer than a one-liner, write a JavaScript function and register it. Every expression on the page can then call it by name:

At 70 kg and 175 cm, your BMI is , which counts as .

Registration can happen at any time, even after the page has rendered: outputs that call a function re-run as soon as it's registered. For short names, register what you need: registerFunction("sqrt", Math.sqrt).

To give a single scope its own function, store it as a variable instead: scopeOf(el).set("f", (x) => x * 2).

Conditional text

There's no special element for conditions. Use a ternary, which can return text:

The thermostat is set to 21, so the heating is .

Writing expressions inside HTML

Errors and missing values

Expressions are compiled with new Function. If your site sends a Content-Security-Policy header, it needs to allow 'unsafe-eval'.

Formats

The format attribute (on <t-num>, <t-var> and <t-out>) and the optional argument of \val[…]{…} control how a value is displayed. A format is either printf-style or the name of a registered format.

printf-style

FormatValueShows
%d4.65 (rounded to an integer)
%.2f3.141593.14
%f22.000000 (six decimals, as in C)
%,d12345671,234,567
%+.1f2+2.0 (always show the sign)
$%,.2f1647.009$1,647.01
%d km4242 km
%s"monthly"monthly
%%a literal %

Text around the placeholder is kept, so prefixes and suffixes need no extra attributes.

Named formats

NameValueShows
percent0.25626% (multiplies by 100)
dollars1499.5$1,500
int2.53

Register your own from JavaScript. The function receives the value and returns a string:

import { registerFormat } from "/tangle.js";

registerFormat("hz", (v) => (v < 1000 ? `${v.toFixed(0)} Hz` : `${(v / 1000).toFixed(2)} kHz`));

Without a format

0.25 is , or per mille, or , or out of $9,999.