Learn · Lesson 2 of 6

Templates

  1. Read
  2. Component
  3. Lists
  4. Conditions
  5. Quiz
  6. Done

Templates

A template is HTML with a few additions: holes for values, inputs for components, and blocks for lists and conditions. All of it runs on the server; the browser gets plain HTML.

Read #

Component #

Make a component that takes a name:

src/components/greeting.tscl

tscl
@input name: string

<p>Hello, {{ name }}!</p>

Use it from a page, passing the input in square brackets:

src/pages/index.tscl

tscl
@import greeting from '../components/greeting.tscl'

<greeting [name]="'world'" />

Hello, world!

Lists #

Put some data in a module and repeat over it:

src/pages/index.tscl

tscl
@import { posts } from '../data/posts.ts'

<ul>
  @for (post of posts; track post.id) {
    <li>{{ $index + 1 }}. {{ post.title }}</li>
  } @empty {
    <li>No posts yet.</li>
  }
</ul>
  • 1. Hello
  • 2. Templates

Conditions #

Show something only when it applies:

tscl
@if (posts.length > 1) {
  <p>{{ posts.length }} posts</p>
} @else {
  <p>Just one post</p>
}

A mistake in a template, such as an unclosed block, fails the build with the file, line and column.

Quiz #

A post title contains <b>. What does {{ post.title }} print?

Show the answer

Answer: The characters <b>, escaped

Holes always escape their value, so <b> shows as text and can't change the page's markup.

Done #

You can print values, compose components, repeat and choose. Next: make part of a page interactive.

In the docs: Holes, Inputs, Lists, Conditionals.