v2.0.3

Text Interpolation

Last updated


How RJS resolves {{ }} in text nodes, and which value helpers it supports.

Resolution


#FIT_TEXT (top level) / #FIT_TEXT_IN_ARRAY / #FIT_TEXT_IN_OBJECT (inside :for) scan text nodes for {{ ... }} and resolve each match through #GET_VALUE, which supports:

Helpers


HelperBehavior
{{ key.path }}Dot-path lookup into data, walked layer by layer via #GET_VALUE_FROM_LAYERS
{{ CALC(key + n) }}Arithmetic: + - * / % with n read through parseInt, applied via #CALC
{{ LENGTH(key) }}Object.keys(value).length for plain objects, value.length otherwise
{{ UPPER(key) }} / {{ LOWER(key) }}.toUpperCase() / .toLowerCase()
{{ DATE(key, format) }}Parses key as a Unix timestamp and formats it (see Number.$format in Date and Number Extensions)

  1. <div id="app">
  2. <p>Name: {{ user.name }}</p>
  3. <p>Upper: {{ UPPER(user.name) }} / Lower: {{ LOWER(user.role) }}</p>
  4. <p>Next year: {{ CALC(user.age + 1) }}</p>
  5. <p>Tags: {{ LENGTH(tags) }}</p>
  6. <p>Joined: {{ DATE(joined, YYYY-MM-DD) }}</p>
  7. </div>
  8. <script>
  9. "#app".RJS({
  10. data: {
  11. user: { name: "Pardn", role: "ADMIN", age: 30 },
  12. tags: ["dom", "template", "zero-dependency"],
  13. joined: 1704110400
  14. }
  15. });
  16. </script>
Live preview · @pardnchiu/renderjs@2.0.3

First Child Node of the Root


When the root element's first child node is an element (no text, whitespace included, before it), that element's own {{ }} text is left as written; later children and deeper descendants still render. A template written with a line break after the opening tag, like the example above, always starts with a text node:
  1. <div id="a"><p>{{ msg }}</p><p>{{ msg }}</p></div>
  2. <div id="b">
  3. <p>{{ msg }}</p>
  4. </div>
  5. <script>
  6. "#a".RJS({ data: { msg: "rendered" } });
  7. "#b".RJS({ data: { msg: "rendered" } });
  8. console.log("a:", "a".$.textContent);
  9. console.log("b:", "b".$.textContent.trim());
  10. </script>
Live preview · @pardnchiu/renderjs@2.0.3

Embedded Text


REGEX_TEXT also matches a value embedded inside surrounding literal text (prefix {{ key }} suffix), preserving the prefix/suffix when substituting.
中文