len(value)
Return the length (in characters) of the rendered value.
<% echo len(123.45) %>
6A task-oriented reference for the functions available in the official Reference Distribution.
Start with the group that matches your task. Each entry gives its signature, what it is for, and a short example. echo writes output, but it is language syntax rather than a built-in function.
Most helpers are available in the Reference Distribution. If you are using another Polonio implementation, this table shows which capability provides each group. For a complete implementation inventory, see the built-in inventory.
| Layer | Examples | Profile availability |
|---|---|---|
| Language Core | type, to_string, to_number, count | All profiles |
| Standard Library | strings, collections, math, dates, html_escape | Reference Standard Library, Web Runtime, Data Runtime, Reference Distribution |
| Template Runtime | print, println | Template Runtime, Reference Distribution |
| Web Runtime | request/response, sessions, CSRF, uploads, send_file, send_mail | Web Runtime, Reference Distribution |
| Data Runtime | file_*, dir_*, db_* | Data Runtime, Reference Distribution |
Use canonical names in new code: to_string, html_escape, http_status, and http_header. The older aliases remain supported for compatibility.
Operate on any input coerced to a string.
| Function | Description |
|---|---|
len(value) | Return the length (in characters) of the rendered value. |
substr(text, start[, length]) | Slice text at the given start (negative values count from the end) and optional length. |
lower(text) | Convert ASCII characters to lowercase. |
upper(text) | Convert ASCII characters to uppercase. |
trim(text) | Strip whitespace on both ends. |
replace(text, from, to) | Replace every occurrence of one substring with another. |
split(text, sep) | Split into an array of segments using the separator. |
contains(haystack, needle) | Return true if the substring exists. |
starts_with(text, prefix) | Return true if text begins with prefix. |
ends_with(text, suffix) | Return true if text ends with suffix. |
html_escape(value) | Escape &, <, >, " and ' for HTML output. Compatibility alias: htmlspecialchars. |
len(value)Return the length (in characters) of the rendered value.
<% echo len(123.45) %>
6substr(text, start[, length])Slice text at the given start (negative values count from the end) and optional length.
<% echo substr("polonio", -3) %>
niolower(text)Convert ASCII characters to lowercase.
<% echo lower("Hola") %>
holaupper(text)Convert ASCII characters to uppercase.
<% echo upper("hola") %>
HOLAtrim(text)Strip whitespace on both ends.
<% echo trim(" hi
") %>
hireplace(text, from, to)Replace every occurrence of one substring with another.
<% echo replace("a-b-a", "-", "/") %>
a/b/asplit(text, sep)Split into an array of segments using the separator.
<% var parts = split("a,b,c", ",") %>
<% echo parts[1] %>
bcontains(haystack, needle)Return true if the substring exists.
<% echo contains("preview", "view") %>
truestarts_with(text, prefix)Return true if text begins with prefix.
<% echo starts_with("docs/home", "docs/") %>
trueends_with(text, suffix)Return true if text ends with suffix.
<% echo ends_with("index.html", ".html") %>
truehtml_escape(value)Compatibility alias: htmlspecialchars(value). Both names have identical behavior.
Escape &, <, >, " and ' for HTML output.
<% echo html_escape("Rock & Roll") %>
Rock & RollManipulate ordered collections.
| Function | Description |
|---|---|
count(arrayOrObject) | Return element (array) or key (object) count. |
push(array, value) | Append and return the new length. |
pop(array) | Remove and return the last element (or null). |
shift(array) | Remove and return the first element. |
unshift(array, value) | Insert at the beginning and return the new length. |
concat(a, b) | Return a new array containing both inputs. |
join(array, sep) | Join elements into a string using the separator. |
slice(array, start[, length]) | Return a shallow slice from start with optional length. |
range(count) | Produce [0, 1, ..., count-1]. |
count(arrayOrObject)Return element (array) or key (object) count.
<% echo count([1,2,3]) %>
3push(array, value)Append and return the new length.
<% var todos = ["a"]; echo push(todos, "b") %>
2pop(array)Remove and return the last element (or null).
<% var todos = ["x","y"]; echo pop(todos) %>
yshift(array)Remove and return the first element.
<% var todos = ["x","y"]; echo shift(todos) %>
xunshift(array, value)Insert at the beginning and return the new length.
<% var todos = ["x"]; echo unshift(todos, "y") %>
2concat(a, b)Return a new array containing both inputs.
<% var both = concat([1,2],[3]); echo count(both) %>
3join(array, sep)Join elements into a string using the separator.
<% echo join(["a","b"], ":") %>
a:bslice(array, start[, length])Return a shallow slice from start with optional length.
<% echo count(slice([1,2,3,4], 1, 2)) %>
2range(count)Produce [0, 1, ..., count-1].
<% echo join(range(3), ",") %>
0,1,2Work with string-keyed maps.
| Function | Description |
|---|---|
keys(object) | Return sorted keys. |
values(object) | Return values sorted by key order. |
has_key(object, name) | Return true if a key exists. |
get(object, name[, default]) | Fetch a value or default (null). |
set(object, name, value) | Assign and return the stored value. |
keys(object)Return sorted keys.
<% echo join(keys({"b":1,"a":2}), ",") %>
a,bvalues(object)Return values sorted by key order.
<% echo join(values({"b":1,"a":2}), ",") %>
2,1has_key(object, name)Return true if a key exists.
<% echo has_key({"x":1}, "x") %>
trueget(object, name[, default])Fetch a value or default (null).
<% echo get({"x":1}, "x", 0) %>
1set(object, name, value)Assign and return the stored value.
<% var obj = {}; echo set(obj, "lang", "es") %>
esNumeric helpers (all arguments must be numbers).
| Function | Description |
|---|---|
abs(n) | Absolute value. |
floor(n) | Round down. |
ceil(n) | Round up. |
round(n) | Round to nearest integer. |
pow(base, exp) | Raise base to exponent. |
sqrt(n) | Square root (throws on negative input). |
min(a, b) | Return the smaller number. |
max(a, b) | Return the larger number. |
rand() | Random floating-point value in [0, 1). |
randint(min, max) | Random integer in inclusive range. |
abs(n)Absolute value.
<% echo abs(-3) %>
3floor(n)Round down.
<% echo floor(3.8) %>
3ceil(n)Round up.
<% echo ceil(3.1) %>
4round(n)Round to nearest integer.
<% echo round(3.6) %>
4pow(base, exp)Raise base to exponent.
<% echo pow(2, 5) %>
32sqrt(n)Square root (throws on negative input).
<% echo sqrt(9) %>
3min(a, b)Return the smaller number.
<% echo min(4, 7) %>
4max(a, b)Return the larger number.
<% echo max(4, 7) %>
7rand()Random floating-point value in [0, 1).
<% echo rand() > 0 %>
truerandint(min, max)Random integer in inclusive range.
<% echo randint(1, 3) >= 1 %>
trueIntrospect and convert runtime values.
| Function | Description |
|---|---|
type(value) | Return the runtime type name. |
to_string(value) | Serialize a value exactly as the output buffer would. Compatibility alias: tostring. |
to_number(value) | Convert strings/bools/null to numbers. |
is_null(value) | Return true if the value is null. |
is_bool(value) | Return true for booleans. |
is_number(value) | Return true for numeric values. |
is_string(value) | Return true for strings. |
is_array(value) | Return true for arrays. |
is_object(value) | Return true for objects. |
is_function(value) | Return true for user or builtin functions. |
type(value)Return the runtime type name.
<% echo type(123) %>
numberto_string(value)Compatibility alias: tostring(value). Both names have identical behavior.
Serialize a value exactly as the output buffer would.
<% echo to_string([1,2]) %>
[1, 2]to_number(value)Convert strings/bools/null to numbers.
<% echo to_number(" 42 ") %>
42is_null(value)Return true if the value is null.
<% echo is_null(null) %>
trueis_bool(value)Return true for booleans.
<% echo is_bool(false) %>
trueis_number(value)Return true for numeric values.
<% echo is_number(3.14) %>
trueis_string(value)Return true for strings.
<% echo is_string("hi") %>
trueis_array(value)Return true for arrays.
<% echo is_array([1]) %>
trueis_object(value)Return true for objects.
<% echo is_object({}) %>
trueis_function(value)Return true for user or builtin functions.
<% echo is_function(type) %>
trueTimestamps are seconds since UNIX epoch (UTC).
| Function | Description |
|---|---|
now() | Return current UNIX timestamp. |
date_format(epoch, pattern) | Token-based formatter (YYYY, MM, DD, HH, mm, SS). |
date_parts(epoch) | Return an object with year/month/day/hour/minute/second. |
date_add_days(epoch, days) | Add days (can be fractional) via 86,400-second units. |
date_parse(text) | Parse YYYY-MM-DD or YYYY-MM-DD HH:MM:SS/T. |
now()Return current UNIX timestamp.
<% echo now() > 0 %>
truedate_format(epoch, pattern)Token-based formatter (YYYY, MM, DD, HH, mm, SS).
<% echo date_format(0, "YYYY-MM-DD") %>
1970-01-01date_parts(epoch)Return an object with year/month/day/hour/minute/second.
<% var p = date_parts(0); echo p["year"] %>
1970date_add_days(epoch, days)Add days (can be fractional) via 86,400-second units.
<% echo date_add_days(0, 1) %>
86400date_parse(text)Parse YYYY-MM-DD or YYYY-MM-DD HH:MM:SS/T.
<% echo date_parse("2026-01-05") %>
1767225600Control how text is emitted from templates.
| Function | Description |
|---|---|
print(...values) | Alias for echo. |
println(...values) | Print followed by newline. |
nl2br(text) | Convert newlines to <br>+
sequences. |
debug(value) | Describe a value on stderr (does not affect HTML). |
print(...values)Alias for echo.
<% print("hi") %>
hiprintln(...values)Print followed by newline.
<% println("hi") %>
hi
nl2br(text)Convert newlines to <br>+
sequences.
<% echo nl2br("a
b") %>
a
bdebug(value)Describe a value on stderr (does not affect HTML).
<% debug(_SERVER) %>
stderrLayer: http_status, http_header, http_content_type, and redirect belong to the Web Runtime and need a ResponseContext; CGI and the development server are the reference distribution's current adapters. urlencode and urldecode belong to the Standard Library and do not require HTTP.
| Function | Description |
|---|---|
http_status(code) | Set the outgoing HTTP status line (100–599). Compatibility alias: status. |
http_header(name, value) | Add or overwrite headers. Compatibility alias: header. |
http_content_type(value) | Set the Content-Type header. |
redirect(target[, status]) | Set Location header plus 3xx status (default 302). |
urlencode(text) | Percent-encode query-string fragments. |
urldecode(text) | Decode percent-encoded strings. |
http_status(code)Compatibility alias: status(code). Both names have identical behavior.
Set the outgoing HTTP status line (100–599).
<% http_status(302) %>
Status: 302http_header(name, value)Compatibility alias: header(name, value). Both names have identical behavior.
Add or overwrite headers.
<% http_header("X-Test", "ok") %>
X-Test: okhttp_content_type(value)Set the Content-Type header.
<% http_content_type("text/plain") %>
Content-Type: text/plainredirect(target[, status])Set Location header plus 3xx status (default 302).
<% redirect("/login") %>
Status: 302 / Location: /loginurlencode(text)Percent-encode query-string fragments.
<% echo urlencode("hola mundo") %>
hola+mundourldecode(text)Decode percent-encoded strings.
<% echo urldecode("hola+mundo") %>
hola mundoLayer: Data Runtime. The official reference distribution provides a sandboxed storage API for reading and writing files. All filesystem access occurs inside the directory referenced by the POLONIO_STORAGE_PATH environment variable, keeping templates away from arbitrary host files.
Rules enforced by every storage builtin:
.. are rejected after normalization.| Function | Description |
|---|---|
file_read(path) | Read a file as a string. |
file_write(path, content) | Write (replace) the contents of a file. |
file_append(path, content) | Append text to a file, creating it if missing. |
file_exists(path) | Return true if a regular file exists. |
file_delete(path) | Delete a regular file if it exists. |
file_size(path) | Return file size in bytes. |
file_modified(path) | Return last modification time in epoch seconds. |
dir_create(path) | Create a directory tree relative to the storage root. |
dir_exists(path) | Return true if a directory exists. |
dir_list(path) | List directory entries (names only) sorted ascending. |
file_read(path)Read the contents of a file inside the storage root and return it as a string.
Arguments:
path — relative path to a regular fileReturns: string containing the file contents.
Errors:
Example:
<%
var text = file_read("notes/welcome.txt")
echo text
%>
file_write(path, content)Write the provided content to a file. The file is created or replaced atomically; parent directories must already exist.
Arguments:
path — relative file path (parent directory must exist)content — value converted to a string before writingReturns: null.
Errors:
Example:
<%
dir_create("drafts")
file_write("drafts/post.txt", "Hello from Polonio!")
%>
file_append(path, content)Append content to a file, creating the file when it does not exist. Parent directories must exist and the target cannot be a directory.
Arguments:
path — relative file pathcontent — value converted to a string before appendingReturns: null.
Errors:
Example:
<%
dir_create("logs")
file_append("logs/app.log", "started\n")
%>
file_exists(path)Test whether a regular file exists at the given relative path.
Arguments:
path — relative file pathReturns: true if a regular file exists, otherwise false.
Errors:
Example:
<% echo file_exists("drafts/post.txt") %>
file_delete(path)Delete a regular file if it exists under the storage root.
Arguments:
path — relative file pathReturns: true if a file was deleted, false if nothing existed.
Errors:
Example:
<%
if file_delete("drafts/post.txt")
echo "Removed draft"
end
%>
file_size(path)Return the size of a regular file in bytes.
Arguments:
path — relative file pathReturns: number representing the byte length.
Errors:
Example:
<%
var size = file_size("drafts/post.txt")
echo "Size: " .. size .. " bytes"
%>
file_modified(path)Return the last modification timestamp of a file as Unix epoch seconds.
Arguments:
path — relative file pathReturns: number representing seconds since the Unix epoch.
Errors:
Example:
<%
var updated_at = file_modified("drafts/post.txt")
echo "Last updated: " .. updated_at
%>
dir_create(path)Create the requested directory (and any intermediate directories) under the storage root.
Arguments:
path — relative directory pathReturns: true whether the directory already existed or was just created.
Errors:
Example:
<% dir_create("uploads/images") %>
dir_exists(path)Check whether a directory exists.
Arguments:
path — relative directory pathReturns: true if the path exists and is a directory; otherwise false.
Errors:
Example:
<%
if dir_exists("uploads")
echo "Uploads ready"
end
%>
dir_list(path)Return an array of entry names (files and directories) sorted ascending for the requested directory.
Arguments:
path — relative directory pathReturns: array of strings (entry names).
Errors:
Example:
<%
var entries = dir_list("posts")
for name in entries
echo "<li>" .. name .. "</li>"
end
%>
Layer: Data Runtime. The official reference distribution includes a SQLite interface for persistent storage. All database files live inside the directory indicated by POLONIO_STORAGE_PATH; paths are resolved relative to that root and may not escape it.
| Function | Description |
|---|---|
db_connect(path) | Open or create a SQLite database file. |
db_close() | Close the current database connection. |
db_query(sql[, params]) | Execute a SELECT statement and return rows. |
db_exec(sql[, params]) | Execute INSERT/UPDATE/DELETE and return affected rows. |
db_last_insert_id() | Return the last inserted row id. |
db_begin() | Start a transaction. |
db_commit() | Commit the current transaction. |
db_rollback() | Roll back the current transaction. |
db_connect(path)Open (or create) a SQLite database inside the storage sandbox.
Arguments:
path — relative path to the database file (parent directory must exist)Returns: null.
Errors:
Example:
<%
dir_create("data")
db_connect("data/app.db")
%>
db_close()Close the active database connection.
Arguments: none.
Returns: null.
Errors:
Example:
<% db_close() %>
db_query(sql[, params])Execute a SELECT statement and return an array of objects (one per row). Column values map to strings, numbers, or null depending on SQLite types:
[
{"id": 1, "name": "Ada"},
{"id": 2, "name": "Grace"}
]
Arguments:
sql — SQL stringparams (optional) — array of positional parameters bound to ?Returns: array of row objects.
Errors:
Example:
<%
var users = db_query("select id, name from users where active = ?", [true])
for user in users
echo user["name"]
end
%>
db_exec(sql[, params])Execute INSERT/UPDATE/DELETE/DDL statements and return the number of rows affected (per sqlite3_changes()).
Arguments:
sql — SQL stringparams (optional) — array of positional parametersReturns: number of rows changed.
Errors: same as db_query.
Example:
<% db_exec("insert into users(name) values(?)", ["Ada"]) %>
db_last_insert_id()Return the row id generated by the most recent insert on the connection.
Arguments: none.
Returns: number (row id).
Errors: database not connected.
Example:
<%
db_exec("insert into users(name) values(?)", ["Ada"])
var id = db_last_insert_id()
%>
db_begin()Start a transaction. Only one transaction can be active at a time.
Arguments: none.
Returns: null.
Errors:
Example:
<%
db_begin()
db_exec("insert into logs(message) values(?)", ["start"])
db_commit()
%>
db_commit()Commit the active transaction.
Arguments: none.
Returns: null.
Errors:
Example:
<%
db_begin()
db_exec("update counters set value = value + 1")
db_commit()
%>
db_rollback()Roll back the active transaction.
Arguments: none.
Returns: null.
Errors:
Example:
<%
db_begin()
db_exec("delete from users where id = ?", [user_id])
db_rollback()
%>
Layer: Web Runtime. These APIs require a Web Runtime request context; CGI and the development server are the reference distribution's current adapters. Calls made without the required context raise a runtime error. Argument mismatches also raise runtime errors.
request_body()var raw = request_body().request_header(name)request_header("Content-Type").request_headers()keys(request_headers()).request_json()var data = request_json().cookies()cookies()["theme"].Require POLONIO_SESSION_SECRET; otherwise they raise an error. Data is stored in a signed cookie and persists only when the response can emit the updated cookie.
session_get(key[, default])session_get("user_id").session_set(key, value)session_set("flash", "Saved").session_unset(key)session_unset("flash").session_clear()session_clear().random_token(bytes)random_token(32).csrf_token()<input value="<% echo csrf_token() %>">.csrf_verify(token)if csrf_verify(_POST["csrf"]).hash_password(password)var hash = hash_password("secret").verify_password(password, hash)verify_password(input, hash).upload_save(file, path)POLONIO_STORAGE_PATH. Example: upload_save(_FILES["photo"], "uploads/photo.bin").send_file(path[, opts])content_type and/or download_name, finalizes the CGI/server response, and returns null. Missing/unsafe files raise errors. Example: send_file("reports/latest.txt").send_mail(to, subject, body[, headers]).eml file to storage outbox and returns its path. Reserved/injected headers raise errors. It does not send SMTP mail. Example: send_mail("[email protected]", "Hi", "Body").http_status(code) has the compatibility alias status(code); http_header(name, value) has header(name, value). Both aliases have identical behavior, including response effects. http_content_type(value) sets a string content type. redirect(target[, status]) accepts a string target and optional 3xx-compatible number, sets Location/status, and returns null.
html_escape(value) has compatibility alias htmlspecialchars(value); to_string(value) has compatibility alias tostring(value). Both pairs have identical successful behavior.