Skip to main content

Expressions

Using {{ expressions }}

The {{...}} construct in HTML templates is used for expression evaluation in Cog. It's a way to display the result of an expression, which can include variables from the state, directly in the HTML.

When you put an expression inside {{}} in your HTML, Cog will automatically evaluate it and replace the {{}} with the result. This is done every time the state changes, ensuring that the displayed result is always up-to-date.

<div>{{ count * 2 }}</div>

In this example, {{ count * 2 }} will be replaced with the result of multiplying the current value of the count variable from the state by 2. If count changes, the content of the <div> will automatically update to show the new result.

Expression dependencies

Cog silently adds dependencies to every expression and uses this information to figure out if expression needs to be re-evaluated. For example, if the div has multiple expressions using different state variables like so:

<div>{{ a }} + {{ b }} = {{ a + b }}</div>
Reactive Node Expressions
const divExpressions = [
{
value: "{{ a }}",
dependency: ["a"],
},
{
value: "{{ b }}",
dependency: ["b"],
},
{
value: "{{ a + b }}",
dependency: ["a", "b"],
},
];

If we update the a state variable only {{ a }} and {{ a + b }} will be re-evaluated, expression {{ b }} will use a cached value.