Share a function

Cow modules hold reusable code, and includes hold reusable markup. This guide shows you how to share a function between pages, render one file inside another, and pass page values to a helper.
Give a module named or default exports, then import them from a page or another module.
_greetings.cow
<?ts
export function greet(name: string): string {
  return 'Hello, ' + name + '!'
}
index.cow
<?js
import { greet } from './_greetings.cow'
?>
<h1><?= h(greet('Clover')) ?></h1>
Output — /
<h1>Hello, Clover!</h1>
Warning: The underscore keeps this helper private over HTTP. Importing a file does not make it private. Without the underscore, visitors can request the helper’s URL.

What a module can contain

Imported Cow modules contain code tags, with optional whitespace around them. They support named and default exports, re-exports, and top-level await. HTML and echo blocks belong in rendered pages or includes.

Reuse markup with an include

_welcome.cow
<p>Hello, <?= h(locals.name) ?>!</p>
index.cow
<?js await include('./_welcome.cow', { name: 'Clover' }) ?>
Output — /
<p>Hello, Clover!</p>
include() renders another file into the current response. Its input is available as locals. Await includes in order.
To choose between the two: imports return module exports, and includes produce output.

Pass page values to a helper

_account.cow
<?js
export function requestedName(req) {
  return req.get('name') || 'visitor'
}
account.cow
<?js
import { requestedName } from './_account.cow'
?>
<p>Hello, <?= h(requestedName(req)) ?>.</p>
Output — /account?name=Clover
<p>Hello, Clover.</p>
Page values such as req, res, and cow are not module globals. Pass them to a helper function when it needs them.
A module’s bindings are shared within a request. Saved sessions and database records persist separately.