standout-render 10.0.0

Styled terminal rendering with templates, themes, and adaptive color support
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
# Templating

`standout-render` uses a two-pass templating system that combines a template engine for logic and data binding with a custom BBCode-like syntax for styling. This separation keeps templates readable while providing full control over both content and presentation.

The default engine is MiniJinja (Jinja2-compatible), but alternative engines are available. See [Template Engines](template-engines.md) for options including a lightweight `SimpleEngine` for reduced binary size.

---

## Two-Pass Rendering Pipeline

Templates are processed in two distinct passes:

```text
Template + Data → [Pass 1: MiniJinja] → Text with style tags → [Pass 2: BBParser] → Final output
```

**Pass 1 - MiniJinja**: Standard template processing. Variables are substituted, control flow executes, filters apply.

**Pass 2 - BBParser**: Style tag processing. Bracket-notation tags are converted to ANSI escape codes (or stripped, depending on output mode).

### Pipeline Example

```text
Template:     [title]{{ name }}[/title] has {{ count }} items
Data:         { name: "Report", count: 42 }

After Pass 1: [title]Report[/title] has 42 items
After Pass 2: \x1b[1;36mReport\x1b[0m has 42 items  (or plain: "Report has 42 items")
```

This separation means:

- Template logic (loops, conditionals) is handled by MiniJinja—a mature, well-documented engine
- Style application is a simple, predictable transformation
- You can debug each pass independently

---

## MiniJinja Basics

MiniJinja implements Jinja2 syntax, a widely-used templating language. Here's a quick overview:

### Variables

```jinja
{{ variable }}
{{ object.field }}
{{ list[0] }}
```

### Control Flow

```jinja
{% if condition %}
  Show this
{% elif other_condition %}
  Show that
{% else %}
  Default
{% endif %}

{% for item in items %}
  {{ loop.index }}. {{ item.name }}
{% endfor %}
```

### Filters

```jinja
{{ name | upper }}
{{ list | length }}
{{ value | default("N/A") }}
{{ text | truncate(20) }}
```

### Comments

```jinja
{# This is a comment and won't appear in output #}
```

For comprehensive MiniJinja documentation, see the [MiniJinja documentation](https://docs.rs/minijinja).

### Booleans and None

Standout renders these the Rust way — `true`, `false`, `none` — not the Jinja2
way MiniJinja itself uses (`True`, `False`, `None`). This holds for
interpolation, loop and `set` bindings, `| string`, `| join`, sequence and map
literals, standout's own filters, and table cells:

```jinja
{{ flag }}                {# true #}
{{ missing }}             {# none #}
{{ flags }}               {# [true, false, none] #}
{{ flags | join(", ") }}  {# true, false, none #}
```

Two exceptions:

- The `~` concatenation operator formats inside MiniJinja's evaluator, which
  exposes no hook: `{{ "x" ~ flag }}` yields `xTrue`. Write `{{ "x" }}{{ flag }}`
  or `{{ "x" ~ flag | string }}`.
- Structured output (JSON, YAML, CSV, NDJSON) skips templates entirely, so
  those modes follow their format's own rules: JSON, YAML and CSV serialize
  your data as the document, and NDJSON writes it inside a
  `{"type":"result","data":…}` line.

If you build a `minijinja::Environment` yourself, use
`standout_render::template::new_environment()` — or call `register_filters` on
your own environment, which installs the same spelling.

---

## The Trailing-Newline Contract

Two things happen to the newline at the end of a template, and together they
are observable in the bytes a script reads, so they are stated here rather than
discovered by probing.

**The engine consumes exactly one final newline.** This is Jinja's rule and
MiniJinja keeps it. A template file ending in a single `\n` renders with no
trailing newline at all; a file ending in two renders with one.

| Template source | Rendered string |
| --- | --- |
| `{{ name }}` | `x` |
| `{{ name }}\n` | `x` |
| `{{ name }}\n\n` | `x\n` |
| `{{ name }}\n\n\n` | `x\n\n` |

**The process edge appends exactly one newline.** `App::run` writes a handled
command's text with `writeln!`, so what reaches stdout is the rendered string
plus one `\n` — whatever the template ended with.

The practical consequence: a template that ends with one newline and a template
that ends with none produce identical bytes. To end a page with a blank line,
the template needs *two* trailing newlines. Every editor that adds a final
newline on save is therefore invisible here, which is the reason the rule is
worth stating.

---

## Style Tags

Style tags use BBCode-like bracket notation to apply named styles from your theme:

```jinja
[style-name]content to style[/style-name]
```

### Basic Usage

```jinja
[title]Report Summary[/title]
[error]Something went wrong![/error]
[muted]Last updated: {{ timestamp }}[/muted]
```

### Nesting

Tags can nest properly:

```jinja
[outer][inner]nested content[/inner][/outer]
```

### Spanning Lines

Tags can span multiple lines:

```jinja
[panel]
This is a multi-line
block of styled content
[/panel]
```

### With Template Logic

Style tags and MiniJinja work together seamlessly:

```jinja
[title]{% if custom_title %}{{ custom_title }}{% else %}Default Title{% endif %}[/title]

{% for task in tasks %}
[{{ task.status }}]{{ task.title }}[/{{ task.status }}]
{% endfor %}
```

The second example shows dynamic style names—the style applied depends on the value of `task.status`.

### Literal brackets

Pass 2 reads `[` as the start of a style tag. To put a literal `[` in the
output, escape it as `\[`; escape a literal `]` as `\]`:

```jinja
Ready \[y/n\]
Range \[0, 100\]
```

renders as `Ready [y/n]` and `Range [0, 100]`. The escape works in every output
mode, and an escaped bracket is never treated as a tag, so it raises no
[unresolved-tag warning](styling-system.md#unresolved-tag-warning). A `[` that
does not begin a valid tag name (for example `[0, 100]`) is already left
literal, so escaping is only needed when the bracketed text would otherwise
parse as a tag.

This is distinct from MiniJinja's `{{`/`}}` brace escape, which belongs to Pass
1 (see [Template Engines](template-engines.md)) and does not affect the Pass 2
bracket syntax.

---

## Processing Modes

Pass 2 (BBParser) processes style tags differently based on the output mode:

| Mode | Behavior | Use Case |
| ------ | ---------- | ---------- |
| `Term` | Replace tags with ANSI escape codes | Rich terminal output |
| `Text` | Strip tags completely | Plain text, pipes, files |
| `TermDebug` | Keep tags as literal text | Debugging, testing |

### Processing Modes Example

Template: `[title]Hello[/title]`

- **Term**: `\x1b[1;36mHello\x1b[0m` (rendered as cyan bold)
- **Text**: `Hello`
- **TermDebug**: `[title]Hello[/title]`

The "strip tags completely" behavior applies to tags the active theme defines.
An *unknown* tag degrades differently, and an unbalanced unknown tag survives
verbatim even under `Text` — see [Unknown Style
Tags](styling-system.md#unknown-style-tags).

### Setting the Mode

```rust
use standout_render::{render_with_output, OutputMode};

// Rich terminal
let output = render_with_output(template, &data, &theme, OutputMode::Term)?;

// Plain text
let output = render_with_output(template, &data, &theme, OutputMode::Text)?;

// Debug (tags visible)
let output = render_with_output(template, &data, &theme, OutputMode::TermDebug)?;

// Auto-detect based on TTY
let output = render_with_output(template, &data, &theme, OutputMode::Auto)?;
```

### Auto Mode

`OutputMode::Auto` resolves to `Term` or `Text` from the destination's color
capability; the rule is in
[Output Modes](../../../topics/output-modes.md#auto-mode).

---

## Built-in Filters

Beyond MiniJinja's standard filters, `standout-render` provides formatting filters:

### Column Formatting

```jinja
{{ value | col(10) }}                              {# pad/truncate to 10 chars #}
{{ value | col(20, align="right") }}               {# right-align in 20 chars #}
{{ value | col(15, truncate="middle") }}           {# truncate in middle #}
{{ value | col(15, truncate="start", ellipsis="...") }}
```

### Padding

```jinja
{{ "42" | pad_left(8) }}      {# "      42" #}
{{ "hi" | pad_right(8) }}     {# "hi      " #}
{{ "hi" | pad_center(8) }}    {# "   hi   " #}
```

### Truncation

```jinja
{{ long_text | truncate_at(20) }}                   {# "Very long text th..." #}
{{ path | truncate_at(30, "middle", "...") }}      {# "/home/.../file.txt" #}
{{ text | truncate_at(20, "start") }}              {# "...end of the text" #}
```

### Display Width

```jinja
{% if value | display_width > 20 %}
  {{ value | truncate_at(20) }}
{% else %}
  {{ value }}
{% endif %}
```

Returns visual width (handles Unicode—CJK characters count as 2).

### Style Application

```jinja
{{ value | style_as("error") }}                    {# wraps in [error]...[/error] #}
{{ task.status | style_as(task.status) }}         {# dynamic: [pending]pending[/pending] #}
```

---

## Template Registry

When using the `Renderer` struct, templates are resolved by name through a registry:

```rust
use standout_render::Renderer;

let mut renderer = Renderer::new(theme)?;

// Add inline template
renderer.add_template("greeting", "Hello, [name]{{ name }}[/name]!")?;

// Add directory of templates
renderer.add_template_dir("./templates")?;

// Render by name
let output = renderer.render("greeting", &data)?;
```

### Resolution Priority

1. **Inline templates** (added via `add_template()`)
2. **Directory templates** (from `add_template_dir()`)

### File Extensions

Supported extensions (in priority order): `.jinja`, `.jinja2`, `.j2`, `.stpl`, `.txt`

When you request `"report"`, the registry checks:

- Inline template named `"report"`
- `report.jinja` in registered directories
- `report.jinja2`, `report.j2`, `report.stpl`, `report.txt` (lower priority)

The `.stpl` extension is for SimpleEngine templates. See [Template Engines](template-engines.md) for details.

### Template Names

Template names are derived from relative paths:

```text
templates/
├── greeting.jinja       → "greeting"
├── reports/
│   └── summary.jinja    → "reports/summary"
└── errors/
    └── 404.jinja        → "errors/404"
```

---

## Including Templates

Templates can include other templates using MiniJinja's include syntax:

```jinja
{# main.jinja #}
[title]{{ title }}[/title]

{% include "partials/header.jinja" %}

{% for item in items %}
  {% include "partials/item.jinja" %}
{% endfor %}

{% include "partials/footer.jinja" %}
```

This enables reusable components across your application.

---

## Context Variables

Beyond your data, you can inject additional context into templates:

```rust
use standout_render::{render_with_vars, OutputMode};
use std::collections::HashMap;

let mut vars = HashMap::new();
vars.insert("version", "1.0.0");
vars.insert("app_name", "MyApp");

let output = render_with_vars(
    "{{ app_name }} v{{ version }}: {{ message }}",
    &data,
    &theme,
    OutputMode::Term,
    vars,
)?;
```

When handler data and context variables have the same key, **handler data wins**. Context is supplementary.

---

## Structured Output

For machine-readable output (JSON, YAML, CSV, NDJSON), templates are bypassed entirely:

```rust
use standout_render::{render_auto, OutputMode};

// Template is used for Term/Text modes
// Data is serialized directly for Json/Yaml/Csv; Ndjson wraps it in a result entry
let output = render_auto(template, &data, &theme, OutputMode::Json)?;
```

| Mode | Behavior |
| ------ | ---------- |
| `Term` | Render template, apply styles |
| `Text` | Render template, strip styles |
| `TermDebug` | Render template, keep style tags |
| `Json` | `serde_json::to_string_pretty(data)` |
| `Yaml` | `serde_yaml::to_string(data)` |
| `Csv` | One row per flat record; a nested value is a render error |
| `Ndjson` | One compact line, `{"type":"result","data":…}` |

This means your serializable data types automatically support structured output without additional code.

---

## Validation

Check templates for unknown style tags before deploying:

```rust
use standout_render::validate_template;

validate_template(template, &sample_data, &theme)?;
```

The error lists every unknown or unbalanced tag.

---

## API Reference

### Render Functions

```rust
use standout_render::{
    render,                  // Basic: template + data + theme
    render_with_output,      // With explicit output mode
    render_with_mode,        // With output mode + color mode
    render_with_vars,        // With extra context variables
    render_auto,             // Auto-dispatch template vs serialize
    render_auto_with_context,
};

// Basic
let output = render(template, &data, &theme)?;

// With output mode
let output = render_with_output(template, &data, &theme, OutputMode::Term)?;

// With color mode override (for testing)
let output = render_with_mode(template, &data, &theme, OutputMode::Term, ColorMode::Dark)?;

// Auto (template for text modes, serialize for structured)
let output = render_auto(template, &data, &theme, OutputMode::Json)?;
```

### Renderer Struct

```rust
use standout_render::Renderer;

let mut renderer = Renderer::new(theme)?;
renderer.add_template("name", "content")?;
renderer.add_template_dir("./templates")?;

let output = renderer.render("name", &data)?;
let output = renderer.render_with_mode("name", &data, OutputMode::Text)?;
```