Programs and the world / Templates: Ochre
Start here01
The language02
- 01The basics
- 02Values and numbers
- 03Variables
- 04Calls and expressions
- 05Conditions and loops
- 06Strings
- 07Arrays and hashes
- 08Classes and records
- 09Traits and enums
- 10Blocks
- 11Methods
- 12Imports and exports
- 13Foreign files
- 14Failures
Programs and the world03
- 01Files, input and output
- 02JSON, time, URLs and random numbers
- 03Html and forms
- 04Templates: Ochre
- 05Built-in methods
Kiln04
03 Programs and the world / 04
Templates: Ochre
HTML with Hematite in it: checked like code, and escaped for wherever a value goes.
Ochre is how pages are written: an Ochre template is a .och file, written in Hematite's own way, a line for each element, attribute and piece of text. Four things make a template safe to write and easy to trust:
Ochre.och
- Says what it takes
- Its
takesnames every value the template needs, a line each, with its type. - Checked like code
- Every mistake in a template is found before running, at its place in the
.ochfile. - Escaped where it lands
- Text put in a page is escaped, and a value can't go where escaping wouldn't make it safe.
- Only shows
- Values are worked out before, in a method, and passed in.
A template
This template lists people. Its first lines say what it needs: the file whose types it uses, another template it shows, and what it takes. An element is a line that starts with its name; its attributes follow, a line each; then what's in it; and end closes it, as end closes every block.
import "../models"
import "row.och" as row
takes
users: [User]
title: String
end
h1 title
# Everyone, one row each.
ul
class: "people"
users.each do (user)
row.render(user: user)
end
end
if users.length == 0
p "Nobody yet."
else
p "#{users.length} people."
endShowing it
A template becomes a method, render, which takes what its takes says and gives Html. A .hem file imports it with a name, and calls it with every argument named:
import "views/users.och" as users_page
const page = users_page.render(users: users, title: "People")
print(page)What a template holds
These are all the lines there are:
| In a template | Does |
|---|---|
div | an element: its attributes come next, then what's in it, then end |
p title, a "Cart" | an element with its opening text on its line: whole on that line, or with its attributes and the rest of what it holds indented under it, then end |
class: "card", hx-post: "/cart" | an attribute of the element above it, a line each, before what's in the element, named as HTML names it |
"Hello, #{name}." | text: written out escaped (< becomes <), each #{value} put in as a value is |
title, card.render(card: card) | a value on a line of its own: text is escaped, Html goes in as it is |
if ..., else if ..., else | shows a part only sometimes |
items.each do (item), do (item, index) | shows a part for each item |
when value and is A.b | shows one part for each value of an enum; every value is listed |
end | closes an element, an if, each or when, takes, and a component's client |
import "shop", import "parts/card.och" as card | at the top: the files whose types and methods it uses, and other templates |
takes | after the imports: what render takes, a parameter on each line below it (user: User, no commas), then end; without it, nothing |
doctype | <!doctype html>, at the top of a layout |
space | one space in the page, between two elements |
# ... | a comment, on a line of its own |
Elements and text
- Elements are HTML's and SVG's. An element or an attribute that isn't one, or an attribute on an element it doesn't belong to, is an error. Any element takes
data-andaria-attributes, and htmx'shx-ones. - Void elements (
input,img,br,meta,link,hr) hold nothing: their attributes, thenend, or alone on their line (br). - An element's text, when it opens with text, is on its line, always. An element that holds more than that line, its attributes or more text and elements, has them indented under it, and
endcloses it; one with nothing indented under it is whole on its line. - Nothing goes into the page between what's written. A sentence with a link in it is written in pieces, its spaces in its strings:
"Read ", then anawith itshref, then" first.". spacealone on its line puts one space in the page, as between two elements:span price, thenspace, thenspan old_price. (hem fmtwrites a line of just" "this way.)- A value alone on its line named like an element (
title,label), or namedspace, would be read as the element (or the space): show it as an element's text (h1 title), or in a string ("#{title}"). - In a
scriptor astyle, a string goes in as it's written; a value can't go there (see Where values can go).
Putting values in
- A value shows text, numbers,
trueorfalse, enum values (by name:owner, notRole.owner) andHtml. A value that might be nil must be checked first, as anywhere, except as the whole of an attribute's value (see Attributes). - Another template's page is
Html, so it goes in as it is: that's how a template uses another, likerowabove, and how a layout wraps a page (it takescontent: Html). - A template only shows things: its lines are the ones above, and nothing else. Every mistake in a template is found before running, at its place in the
.ochfile. hem rundoesn't run a template by itself: it's shown from a.hemfile.
A template works nothing out
A template shows what it's given, and asks only what its values already answer. Hematite works things out, in a method, and passes the answers in: so a template always reads as the page it makes.
- A value in a template is a name, a field, a literal, a call (to format a value, like
euros(price), or to show another template), orif ... then ... elsewhose question is one of these. Text and values are written together in a string,"#{count} people", and each#{}holds a value like these. - The questions a template asks: a Boolean (
if size.chosen), whether a value is there (x != nil,x == nil), and whether a list is empty (items.length == 0,items.length > 0). - Anything else is an error that says what to do instead: arithmetic (
price * quantity), other comparisons (tab.path == current),and,orandnot, picking withitems[0], making a list, a hash or a record,whenas a value (awhenblock chooses markup), and lines that aren't markup (const, a block other thaneach's). - What the page needs is passed in already worked out: a field
cost, a Booleancurrent, aString?that's nil when there's nothing to show.
import "../shop"
takes
lines: [Line]
end
lines.each do (line)
p euros(line.price * line.quantity)
endviews/lines.och:8:22: error: a template shows what it's given, and works nothing out: '*' is worked out in Hematite, and the result passed in, like a field 'cost'Attributes
An attribute whose whole value is one value can be left out, so an element is written once, however its attributes change:
- An attribute that's there or not takes
trueorfalse:checked: chosenwritescheckedwhen it's true, and nothing when it's false. These are HTML's attributes that are there or not:checked,disabled,selected,required,readonly,multiple,hidden,open,autofocus,novalidate,formnovalidate,inert,default,reversed,async,defer,nomodule,playsinline,loop,muted,controls,autoplay,allowfullscreen,itemscopeandismap. Their value is one Boolean, and nothing else. - Any other attribute is left out when its value is nil:
aria-current: if current then "page" else nil. This is the one place a value that might be nil goes without being checked first. - To change part of a value, like one of an element's classes, put an inline
ifin it:class: "py-3 #{if current then "font-bold" else "font-normal"}". trueandfalsego in no other attribute: write the text for each case instead, with an inlineif.
The code that shows the page works out what's chosen and what's current, and the records it passes say so:
export record Size
name: String
chosen: Boolean
sold_out: Boolean
end
export record Tab
path: String
label: String
current: Boolean
endA list of sizes to choose from, each one checked if it's chosen and disabled if it's sold out, and its label in bold when it's chosen:
import "../shop"
takes
sizes: [Size]
end
fieldset
sizes.each do (size)
label
class: if size.chosen then "font-bold" else "font-normal"
input
type: "checkbox"
name: "size"
value: size.name
checked: size.chosen
disabled: size.sold_out
end
" #{size.name}"
end
end
endTabs, the current one marked for screen readers:
import "../shop"
takes
tabs: [Tab]
end
nav
tabs.each do (tab)
a tab.label
href: tab.path
aria-current: if tab.current then "page" else nil
end
end
endShown with a few sizes and tabs:
import "shop"
import "views/sizes.och" as sizes
import "views/tabs.och" as tabs
const shown = [
new Size(name: "S", chosen: false, sold_out: true),
new Size(name: "M", chosen: true, sold_out: false),
]
print(sizes.render(sizes: shown))
print(
tabs.render(
tabs: [
new Tab(path: "/women", label: "women", current: false),
new Tab(path: "/men", label: "men", current: true),
],
),
)Prints
<fieldset><label class="font-normal"><input type="checkbox" name="size" value="S" disabled> S</label><label class="font-bold"><input type="checkbox" name="size" value="M" checked> M</label></fieldset>
<nav><a href="/women">women</a><a href="/men" aria-current="page">men</a></nav>Where values can go
Escaping makes text safe in HTML's text and in attribute values, so that's where a value can go. Elsewhere, the template is an error:
| Place | |
|---|---|
text, title: ..., class: "card #{size}" | fine |
inside a script or a style | an error: escaping doesn't make JavaScript or CSS safe; put the value in a data- attribute, and read it from the script |
onclick and every on... attribute | not attributes a template writes (a component's on-click is its own) |
style: ... | an error: choose a class, or use a data- attribute |
The same holds when a value is an attribute's whole value: true, false and nil only decide whether the attribute is there.
Links
A value that starts a link, like href: link (or src, action and the like), may lead anywhere a page can, but not to code: a link that would run code when followed (javascript:..., data:...) becomes about:invalid#hem-blocked-url.
Components
What changes only the page, like choosing a size, counting, or showing what's typed as it's typed, needs nothing from the server. A template with a client block is a component: the browser works it out, in Hematite. The block is the third part of the template's head, after its imports and what it takes:
takes
start: Int
end
client
var count: Int = start
def add()
count = count + 1
end
def label(): String
return if count == 1 then "1 item" else "#{count} items"
end
end
button label()
type: "button"
on-click: add()
endimport "views/counter.och" as counter
print(counter.render(start: 2)) # prints <div data-hem-component="views_counter" data-hem-takes="{"start":2}" style="display: contents"><button type="button" data-hem-on-click="0">2 items</button></div><script type="module" src="/.hem/components.js"></script>The block holds the component's state, vars with their types and starting values, worked out from what the template takes; and its methods, defs. The template's values show the state and call the methods, and still work nothing out; only the block's methods change the state.
on-click: add() calls a method when the event happens: click, input, change, submit (which then doesn't send the form) or keydown. It's one call, checked as any call is, at its place in the template. A method it calls can't fail: one that calls something that can handles the failure there, with rescue. bind-value: query shows a String of the state in a field, and typing changes it; bind-checked: chosen does the same with a Boolean, for a checkbox.
render shows a component as any template, in an element that names it and holds what it took (and that a layout around it doesn't see), so the page is whole without JavaScript. What it takes goes to the browser, so it's data: not Html.
In the browser, the page loads /.hem/components.js, which starts Hematite's own VM, built for WebAssembly, on the app's components. The VM makes the same component from what it took, runs its methods when things happen, and works out its page again after each event; the page changes where it differs, and nothing else: a field being typed in keeps what's typed. A mistake there, like an index past the end of an array, stops that component, and says where in the browser's console; the rest of the page goes on.
A component runs on the VM the server runs: an Int is 64 bits, and Bytes, times and zones are the same. What a component prints goes to the browser's console.
Program.components() gives the files a page needs for the program's components, by the name each is served at under /.hem/: none when it has no components. Whatever serves the page serves them there (Kiln does for its applications). A program built with hem build carries them, worked out when it was built.
import "views/counter.och" as counter
const files = try Program.components()
print(files.keys.length) # prints 3
print(files.has("components.js")) # prints truecomponents.jsis the page's side: it loads the other two, starts each component the page shows, and passes events to the VM.hematite-<hash>.wasmis the VM, the same for every program: it comes withhem. It's about 430 KB, and about 180 KB sent compressed (Kiln sends it gzipped to a browser that takes it so).components-<hash>.binis the program's components, compiled for the browser: only the code they reach, so the server's own code and text stay on the server. The VM has no time zones of its own: this brings the ones the program names, a few KB each when everyZone.namedhas its name written out, likeZone.named("Europe/Copenhagen"). When one doesn't, the name could be any zone, so it brings them all: about 220 KB, and about 56 KB compressed.- The page names only
components.js, which names the other two. Their names hold a hash of what's in them, so a name always means the same bytes: a server can let browsers keep them for good, and a browser asks again only when they change.
The browser has no files, C, input or arguments, and no package's Rust: a component whose code reaches them makes Program.components() fail, with kind invalid, saying where: views/files.och:9:17: a component runs in the browser, which can't: the browser has no files (File.read).