Component inputs, rendering and slots
Give a component typed inputs by defining a KScript type. Save this as _components/hello-card.kscript.
<import package="KScript.Web" />
<type name="HelloCard" extends="Component">
<field name="name" type="string" />
<fn name="render">
<return value="```html
<p>Hello, {$name}!</p>
```" />
</fn>
</type>import KScript.Web
type HelloCard extends Component {
name: string
fn render() {
return ```html
<p>Hello, {$name}!</p>
```
}
}Add <hello-card name="Sam" /> to index.html to render Hello, Sam!. Use kebab-case for attributes like display-name and underscores for fields like display_name. An attribute that consists of one expression passes its original type. For example, start="{3}" passes an integer.
| Part | How it works |
|---|---|
| Discovery | KScript resolves <item-card /> to a component such as _components/item-card.kscript or _components/item-card.html. |
| Class contract | A script component extends Component and defines fn render(). The html block it returns shows that it draws a page, so the method needs no return type. |
| Inputs | The caller can initialize stored fields using attributes. A field initializer supplies a default. Simple field types also have built-in initial values. |
| Render-time values | HTML can read a field as $title or $.title. Computed fields and component methods can prepare display values. |
| Children | Put <slot /> in the template to render the caller's child markup. |
| Template components | HTML and Markdown components can declare <prop name="title" required />. A companion script can expose load(props: map) and other functions. |
The page may render more than once during an action. Keep render methods, computed values and companion load functions free of writes. Put persistent changes in a live action or a controller. Actions can persist through KScript.Data. File and storage writes require a controller view rendered with @view() and permission from http.write_files. See template props and companion scripts for the template form and its onLoad callback.