# Views & Blade

## Introduction

Blade is the simple, yet powerful templating engine included with Laravel. In Laravel Bash, Blade templates are Bash files that print HTML with heredocs. A heredoc already expands `$variables` and `$(commands)`, so the templates were compiled before you wrote them.

```bash
# resources/views/greeting.blade.sh
cat <<HTML
<h1>Hello, $(e "$name")</h1>
<p>This page was rendered by process $$.</p>
HTML
```

## Rendering Views

```bash
view greeting name="Taylor"
```

Each `key=value` becomes a local variable in the view. The dotted name `posts.show` means `resources/views/posts/show.blade.sh`.

### Passing models

When a value holds exactly one row of query results (a header line and one data line), the view gets an associative array instead of text:

```bash
view posts.show post="$(Post::find 1)"
```

```bash
cat <<HTML
<h1>$(e "${post[title]}")</h1>
HTML
```

## Displaying Data

### Escaping

`{{ $name }}` is `$(e "$name")`. `e` escapes `&`, `<`, `>`, `"` and `'` with parameter expansion, so it doesn't start a program:

```bash
e() {
  local s=${1-}
  s=${s//&/"&amp;"}
  s=${s//</"&lt;"}
  s=${s//>/"&gt;"}
  s=${s//\"/"&quot;"}
  s=${s//\'/"&#39;"}
  printf '%s' "$s"
}
```

> [!WARNING]
> The replacements are in quotes for a reason. Since Bash 5.2, an unquoted `&` in a replacement means "the text that matched", like in `sed`. Without the quotes, `&` becomes `&amp;amp;`, which is not what anyone wants.

### Raw output

`{!! $html !!}` is just `$html`. Be careful, as you would be with Blade.

## Layouts

Every view is wrapped in `resources/views/layouts/app.blade.sh`, which prints `$slot` where the page goes. Views in `layouts/` and `partials/` aren't wrapped.

## Loops

There is no `@foreach`. There is `while`, and `next_row`, which reads the header line first, then fills an associative array with each row:

```bash
declare -A post
while next_row post; do
  cat <<HTML
    <tr>
      <td><a href="/posts/${post[id]}">$(e "${post[title]}")</a></td>
      <td>${post[votes]}</td>
    </tr>
HTML
done <<< "$posts"
```

### Empty fields

Splitting a row with `IFS=$'\t' read` looks right, but tab counts as whitespace, and `read` merges runs of whitespace. A row with an empty field in the middle shifts every field after it one column to the left. So `next_row` swaps each tab for byte `0x1F`, the ASCII *unit separator*, which `IFS` treats literally. It has been waiting since 1963 for someone to use it.

## Why not envsubst?

`envsubst` replaces `$VARIABLES` in a template, which sounds perfect. But it only sees exported variables, it can't run functions like `e`, and it comes from gettext, which isn't always installed. A `sed`-based engine means escaping every value twice, once for HTML and once for `sed`, and getting one of them wrong is an injection. Heredocs need neither.
