sercrod

Data and interpolation

This page explains how Sercrod reads the data attribute on a host <serc-rod> element and how it expands expressions into text using interpolation and *print.

At a glance:

Host data

Every Sercrod host has a single data object. By default it is initialized from the data attribute on <serc-rod>.

<serc-rod id="app"
  data='{
    "title": "Hello Sercrod",
    "user": { "name": "Taro" },
    "count": 0
  }'>

  <p>Welcome, %user.name%!</p>

</serc-rod>

In addition to JSON, the data attribute may also point to an existing variable. For example, when a global json object already exists:

<script>
  const json = { title: "Hello Sercrod", name: "Sercrod" };
</script>

<serc-rod id="app" data="json">
  <h1 *print="title"></h1>
</serc-rod>

Internally, Sercrod wraps the data in a Proxy so that assignments can trigger re-renders.

Text interpolation

Sercrod can expand expressions inside text nodes using interpolation delimiters. By default both the start and end delimiter are %.

<serc-rod data='{"name": "Sercrod", "n": 3}'>
  <p>Hello, %name%!</p>
  <p>n is %n%, n + 1 is %n + 1%</p>
</serc-rod>

Everything between the delimiters is evaluated as an expression in the current scope. The result replaces the whole %...% block.

The delimiters can be changed globally with __Sercrod.config.delimiters if needed.

*print and *textContent

The *print directive writes the evaluated result of an expression into an element’s textContent.

<serc-rod data='{"user": { "name": "Taro" }}'>
  <p *print="user.name"></p>
</serc-rod>

*textContent and n-textContent are synonyms of *print. They exist for projects that prefer a more explicit name.

<serc-rod data='{"count": 3}'>
  <span *textContent="count + 1"></span>
</serc-rod>

Interpolation in attributes

Plain HTML attributes can also contain interpolation blocks. Sercrod resolves them and applies the final string to the attribute.

<serc-rod data='{"name": "Sercrod"}'>
  <input
    type="text"
    placeholder="Hello, %name%!"
  >
</serc-rod>

For attributes that should react to state changes, use bindings such as :value, :class or :style. These are described on the attribute bindings page.

Updating data

Assignments in event handlers update the host data and trigger re-rendering of the affected parts.

<serc-rod data='{"count": 0}'>
  <p *print="count"></p>
  <button @click="count++">Increment</button>
</serc-rod>

See also