Skip to content

k.state ​

View data (ViewData) within the current request rendering context

Execution ContextPrerequisitesTypical Use
Page / Layout / View server scripts and CodeBlocks in HTML renderingWithin a single HTTP request lifecyclePass data to template bindings (k-content, k-for) and downstream scripts

k.state reads and writes key-value entries on the current HTTP request's view data stack for template bindings in pages, layouts, and views (for example k-content="product" or k-for="item in products") and downstream scripts in the same request. Data is discarded at the end of the request and is not persisted across requests.

Quick Start ​

js
const items = k.DB.sqlite.getTable("Product").all()
k.state.set("products", items)
k.page.setTitle("Product List")

const currentProducts = k.state.get("products")

Quick Reference ​

Method / PropertyDescriptionReturns
set(key, value)Push a named entry onto the view data stackvoid
setCurrent(key, value)Write or overwrite a key on the top stack framevoid
get(key)Read key from current view data context (null if missing)any

Differences from k.cache and k.session

APIScopeTypical uses
k.stateView rendering within a single requestController or CodeBlock passes product, breadcrumb to templates
k.cacheSite-level memory, expirableShared computed values across requests
k.sessionVisitor sessionLogin status and temporary cart data

k.state is designed for HTML page rendering flows (page CodeBlocks, layout scripts, and view scripts). In standalone k.api calls that return JSON without rendering templates, set/get stays in the current request script stack and does not emit HTML output.

Methods ​

set() ​

Push named data onto the view data stack (stacked calls follow the rendering engine's data scope rules).

ParameterTypeRequiredDescription
keystringYesKey name referenced in templates
valueanyYesSerializable object or primitive value

Returns: void.

js
const product = { id: "1", name: "Sample" }
k.state.set("product", product)

setCurrent() ​

Write or overwrite a key on the current top stack frame; behaves like set when the stack is empty.

ParameterTypeRequiredDescription
keystringYesKey name
valueanyYesNew value

Returns: void.

js
k.state.set("items", list)
k.state.setCurrent("items", updatedList)

get() ​

Look up view data by key across the current data context and outer stack frames.

ParameterTypeRequiredDescription
keystringYesKey name

Returns: The value stored via set / setCurrent, or null when missing.

js
const product = k.state.get("product")

Example: Passing Data from a Page Script to a Template ​

js
// Page CodeBlock
const items = k.DB.sqlite.getTable("Product").all()
k.state.set("products", items)
k.page.setTitle("Product List")

// Read in another script during the same request
const products = k.state.get("products")

TypeScript Definitions ​

ts
interface kState {
  set(key: string, value: any): void;
  setCurrent(key: string, value: any): void;
  get(key: string): any;
}