Skip to content

HTML is escaped for you

Cross-site scripting happens when a page shows text from a user as HTML. In Novis you write HTML with an html template. Every value you put into it, like {$name}, is escaped:

<?nvs
// This program puts a name that a user typed into an HTML page.
string $name = '<script>alert(1)</script>';
// `{$name}` is a hole in an `html` template. Its value is escaped.
echo html`<p>Hello, {$name}</p>`, "\n";
// `$part` is already HTML, so `{$part}` inserts it without escaping it again.
Core\Html\Markup $part = html`<b>{$name}</b>`;
echo html`<p>{$part}</p>`, "\n";
Output
<p>Hello, &lt;script&gt;alert(1)&lt;/script&gt;</p>
<p><b>&lt;script&gt;alert(1)&lt;/script&gt;</b></p>

The name contains a <script> tag. The page shows it as text, and the browser does not run it.

An html template has the type Core\Html\Markup. You put one piece of markup into another with the same hole, {$part}. That value is already HTML, so it is not escaped a second time.

You do not need to remember an escape function. The safe way is the only way to write it.

Escaping is not enough for a link. In href="{$url}", a URL that starts with javascript: runs a script when a visitor clicks the link. Core\Html::attributes writes a map of attributes into a tag. It leaves out a link with an unsafe URL:

<?nvs
// This program writes a link for each URL. The second URL runs a script.
array<string> $urls = ['https://example.com/', 'javascript:alert(1)'];
foreach ($urls as string $url) {
// `Core\Html::attributes` writes `href` only when the URL is safe.
echo html`<a <?= Core\Html::attributes(['href' => $url, 'class' => ['button', 'big']]) ?>>Open</a>`, "\n";
}
Output
<a href="https://example.com/" class="button big">Open</a>
<a class="button big">Open</a>

The second link has no href, so it does nothing when a visitor clicks it.

Read more in Reference: Core\Html and in step 9 of the Tour.