or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

dimensions.mddocument-structure.mdgraphics-images.mdindex.mdlayout-engine.mdreferences.mdstyling-system.mdtemplate-system.mdtypography-text.md

template-system.mddocs/

0

# Template System

1

2

Comprehensive document template system providing page layouts, headers/footers, document structure configuration, and template-based document generation. The template system enables consistent document formatting and professional layouts across different document types.

3

4

## Capabilities

5

6

### Document Templates

7

8

Core template classes that define overall document structure, page layouts, and formatting rules.

9

10

```python { .api }

11

class DocumentTemplate(TemplateConfiguration):

12

"""

13

Base class for document templates defining structure and layout.

14

15

Provides the foundation for creating different document types with

16

consistent formatting, page layouts, and structural elements.

17

18

Parameters:

19

- name: str, template name identifier

20

- configuration: TemplateConfiguration, template settings

21

"""

22

def __init__(self, name=None, configuration=None): ...

23

24

@property

25

def stylesheet(self): ... # Associated stylesheet

26

@property

27

def parts(self): ... # Document parts configuration

28

29

def document(self, document_tree, stylesheet=None, language=None,

30

backend=None): ... # Create document with this template

31

32

class Article(DocumentTemplate):

33

"""

34

Article template for academic papers, reports, and articles.

35

36

Provides single-column layout with title page, abstract, sections,

37

and appropriate styling for scholarly documents.

38

"""

39

def __init__(self): ...

40

41

class Book(DocumentTemplate):

42

"""

43

Book template for multi-chapter documents and publications.

44

45

Provides book-style layout with chapters, table of contents,

46

index, and appropriate pagination for longer documents.

47

"""

48

def __init__(self): ...

49

```

50

51

### Template Configuration

52

53

Configuration system for customizing template behavior, options, and document structure.

54

55

```python { .api }

56

class TemplateConfiguration(RuleSet):

57

"""

58

Configuration container for template settings and options.

59

60

Manages template-specific settings including page layouts,

61

document parts, styling rules, and behavioral options.

62

63

Parameters:

64

- name: str, configuration name

65

- base: TemplateConfiguration, base configuration to inherit from

66

- **options: configuration option key-value pairs

67

"""

68

def __init__(self, name, base=None, **options): ...

69

70

def get_entry_point_flowables(self, document_part): ... # Get part content

71

def get_page_template(self, document_part, page_type): ... # Get page template

72

73

class TemplateConfigurationFile(TemplateConfiguration):

74

"""

75

Template configuration loaded from file.

76

77

Parameters:

78

- file: str or file-like, path to or open template configuration file

79

"""

80

def __init__(self, file): ...

81

82

class Option:

83

"""

84

Template option descriptor with validation and default values.

85

86

Defines configurable options for templates with type checking,

87

validation, and documentation.

88

89

Parameters:

90

- default: default value for the option

91

- description: str, option description

92

- validator: callable, validation function

93

"""

94

def __init__(self, default, description=None, validator=None): ...

95

```

96

97

### Page Templates

98

99

Page layout templates defining the structure and positioning of page elements.

100

101

```python { .api }

102

class PageTemplate:

103

"""

104

Base class for page layout templates.

105

106

Defines the structure of a page including margins, headers, footers,

107

and content areas with precise positioning and sizing.

108

109

Parameters:

110

- name: str, page template name

111

- page_size: Paper, page dimensions

112

- page_orientation: str, 'portrait' or 'landscape'

113

- left_margin: Dimension, left page margin

114

- right_margin: Dimension, right page margin

115

- top_margin: Dimension, top page margin

116

- bottom_margin: Dimension, bottom page margin

117

"""

118

def __init__(self, name, page_size, page_orientation='portrait',

119

left_margin=None, right_margin=None,

120

top_margin=None, bottom_margin=None): ...

121

122

@property

123

def page_size(self): ... # Page dimensions

124

@property

125

def page_orientation(self): ... # Page orientation

126

@property

127

def body_width(self): ... # Content area width

128

@property

129

def body_height(self): ... # Content area height

130

131

class BodyPageTemplate(PageTemplate):

132

"""

133

Page template for main document content pages.

134

135

Provides standard layout for body text with headers, footers,

136

and content area configuration.

137

"""

138

def __init__(self, page_size, page_orientation='portrait', **margins): ...

139

140

class TitlePageTemplate(PageTemplate):

141

"""

142

Page template for document title/cover pages.

143

144

Specialized layout for title pages with different margins,

145

content positioning, and styling from body pages.

146

"""

147

def __init__(self, page_size, page_orientation='portrait', **margins): ...

148

149

class ContentsPartTemplate(PageTemplate):

150

"""

151

Page template for table of contents and similar navigation pages.

152

153

Optimized layout for multi-column content lists with appropriate

154

spacing and formatting for navigation elements.

155

"""

156

def __init__(self, page_size, columns=1, **kwargs): ...

157

158

class FixedDocumentPartTemplate(PageTemplate):

159

"""

160

Page template for fixed-content document parts.

161

162

Used for document parts with predetermined content and layout

163

that doesn't flow like regular body text.

164

"""

165

def __init__(self, flowables, **kwargs): ...

166

```

167

168

### Page Types and Components

169

170

Specialized page components and type definitions for different parts of documents.

171

172

```python { .api }

173

class BodyPage:

174

"""

175

Definition for main content pages in document body.

176

177

Specifies layout, headers, footers, and content flow for

178

the primary text content of documents.

179

"""

180

def __init__(self, page_template, header=None, footer=None): ...

181

182

class TitlePage:

183

"""

184

Definition for document title/cover pages.

185

186

Specialized page for title content with different layout

187

and formatting from body pages.

188

"""

189

def __init__(self, page_template, content): ...

190

191

class PageNumberFormat:

192

"""

193

Page numbering format and positioning configuration.

194

195

Controls how page numbers are formatted, positioned, and

196

displayed across different document parts.

197

198

Parameters:

199

- format: NumberFormat, numbering format (arabic, roman, etc.)

200

- start: int, starting page number

201

- restart: bool, whether to restart numbering

202

"""

203

def __init__(self, format=NUMBER, start=1, restart=False): ...

204

```

205

206

### Document Parts

207

208

Document part system for organizing content into logical sections with different layouts and numbering.

209

210

```python { .api }

211

class DocumentPart:

212

"""

213

Logical section of document with specific template and numbering.

214

215

Represents distinct parts of documents (front matter, body, appendices)

216

that may have different page templates, numbering, and formatting.

217

218

Parameters:

219

- name: str, part identifier

220

- page_template: PageTemplate, layout for this part

221

- page_number_format: PageNumberFormat, numbering configuration

222

- flowables: list, content for this part

223

"""

224

def __init__(self, name, page_template=None, page_number_format=None,

225

flowables=None): ...

226

227

class FrontMatter(DocumentPart):

228

"""Document front matter (title page, TOC, abstract, etc.)."""

229

230

class Body(DocumentPart):

231

"""Main document body content."""

232

233

class BackMatter(DocumentPart):

234

"""Document back matter (appendices, index, bibliography, etc.)."""

235

```

236

237

### Template Utilities

238

239

Utility functions and classes for template management and document generation.

240

241

```python { .api }

242

def register_template(name, template_class):

243

"""

244

Register template class for use by name.

245

246

Parameters:

247

- name: str, template identifier

248

- template_class: class, DocumentTemplate subclass

249

"""

250

...

251

252

def get_template(name):

253

"""

254

Get registered template by name.

255

256

Parameters:

257

- name: str, template identifier

258

259

Returns:

260

- DocumentTemplate subclass

261

"""

262

...

263

264

class TemplateConfigurationError(Exception):

265

"""Exception for template configuration errors."""

266

267

class PageLayoutError(Exception):

268

"""Exception for page layout errors."""

269

```

270

271

## Usage Examples

272

273

### Basic Template Usage

274

275

```python

276

from rinohtype.template import Article, Book

277

from rinohtype import Document, DocumentTree

278

from rinohtype.structure import Section, Heading

279

from rinohtype.paragraph import Paragraph

280

281

# Create document content

282

content = DocumentTree([

283

Section([

284

Heading("Introduction"),

285

Paragraph("This is the introduction...")

286

])

287

])

288

289

# Use article template

290

article_template = Article()

291

document = article_template.document(content)

292

document.render('article_output')

293

294

# Use book template

295

book_template = Book()

296

book_document = book_template.document(content)

297

book_document.render('book_output')

298

```

299

300

### Custom Template Creation

301

302

```python

303

from rinohtype.template import DocumentTemplate, TemplateConfiguration

304

from rinohtype.template import BodyPageTemplate, TitlePageTemplate

305

from rinohtype.paper import A4

306

from rinohtype.dimension import MM

307

308

class CustomTemplate(DocumentTemplate):

309

"""Custom document template with specific formatting."""

310

311

def __init__(self):

312

# Define page templates

313

body_template = BodyPageTemplate(

314

page_size=A4,

315

left_margin=25*MM,

316

right_margin=25*MM,

317

top_margin=30*MM,

318

bottom_margin=25*MM

319

)

320

321

title_template = TitlePageTemplate(

322

page_size=A4,

323

left_margin=40*MM,

324

right_margin=40*MM,

325

top_margin=50*MM,

326

bottom_margin=50*MM

327

)

328

329

# Create configuration

330

config = TemplateConfiguration('custom')

331

config['body_page'] = body_template

332

config['title_page'] = title_template

333

334

super().__init__('custom', config)

335

336

# Use custom template

337

custom_template = CustomTemplate()

338

document = custom_template.document(content)

339

```

340

341

### Page Layout Configuration

342

343

```python

344

from rinohtype.template import BodyPageTemplate, PageNumberFormat

345

from rinohtype.structure import Header, Footer

346

from rinohtype.reference import Field, PAGE_NUMBER, DOCUMENT_TITLE

347

from rinohtype.text import SingleStyledText

348

from rinohtype.paper import LETTER

349

from rinohtype.dimension import INCH

350

351

# Create page template with headers and footers

352

page_template = BodyPageTemplate(

353

page_size=LETTER,

354

left_margin=1*INCH,

355

right_margin=1*INCH,

356

top_margin=0.75*INCH,

357

bottom_margin=0.75*INCH

358

)

359

360

# Define header content

361

header_content = Header([

362

Paragraph([SingleStyledText("Document Title")])

363

])

364

365

# Define footer with page numbers

366

footer_content = Footer([

367

Paragraph([

368

SingleStyledText("Page "),

369

Field(PAGE_NUMBER),

370

SingleStyledText(" of "),

371

Field(NUMBER_OF_PAGES)

372

])

373

])

374

375

# Configure page numbering

376

page_numbering = PageNumberFormat(

377

format=NUMBER, # Arabic numerals

378

start=1,

379

restart=False

380

)

381

```

382

383

### Multi-Part Document Template

384

385

```python

386

from rinohtype.template import DocumentTemplate, FrontMatter, Body, BackMatter

387

from rinohtype.template import TitlePageTemplate, BodyPageTemplate

388

from rinohtype.number import ROMAN_LC, NUMBER

389

390

class ThesisTemplate(DocumentTemplate):

391

"""Template for academic thesis with multiple parts."""

392

393

def __init__(self):

394

config = TemplateConfiguration('thesis')

395

396

# Title page template

397

title_template = TitlePageTemplate(A4, top_margin=50*MM)

398

399

# Front matter template (TOC, abstract, etc.)

400

front_template = BodyPageTemplate(A4)

401

front_numbering = PageNumberFormat(format=ROMAN_LC, start=1)

402

403

# Body template

404

body_template = BodyPageTemplate(A4)

405

body_numbering = PageNumberFormat(format=NUMBER, start=1, restart=True)

406

407

# Back matter template (appendices, bibliography)

408

back_template = BodyPageTemplate(A4)

409

back_numbering = PageNumberFormat(format=NUMBER, restart=False)

410

411

# Configure document parts

412

config.document_parts = [

413

FrontMatter('front', front_template, front_numbering),

414

Body('body', body_template, body_numbering),

415

BackMatter('back', back_template, back_numbering)

416

]

417

418

super().__init__('thesis', config)

419

```

420

421

### Template Options

422

423

```python

424

from rinohtype.template import Option, TemplateConfiguration

425

426

class ConfigurableTemplate(DocumentTemplate):

427

"""Template with configurable options."""

428

429

# Define template options

430

font_size = Option(11, "Base font size in points")

431

line_spacing = Option(1.2, "Line spacing multiplier")

432

two_column = Option(False, "Use two-column layout")

433

434

def __init__(self, **options):

435

config = TemplateConfiguration('configurable')

436

437

# Apply options

438

for name, value in options.items():

439

if hasattr(self, name):

440

setattr(self, name, value)

441

442

# Configure based on options

443

if self.two_column:

444

config['columns'] = 2

445

else:

446

config['columns'] = 1

447

448

super().__init__('configurable', config)

449

450

# Use with options

451

template = ConfigurableTemplate(

452

font_size=12,

453

line_spacing=1.5,

454

two_column=True

455

)

456

```

457

458

### Template Registration

459

460

```python

461

from rinohtype.template import register_template

462

463

# Register custom template

464

register_template('custom_article', CustomTemplate)

465

466

# Use registered template by name

467

def create_document_with_template(content, template_name):

468

template_class = get_template(template_name)

469

template = template_class()

470

return template.document(content)

471

472

document = create_document_with_template(content, 'custom_article')

473

```

474

475

### Advanced Page Templates

476

477

```python

478

from rinohtype.template import PageTemplate

479

from rinohtype.layout import Container, DownExpandingContainer

480

481

class CustomPageTemplate(PageTemplate):

482

"""Custom page template with special layout."""

483

484

def __init__(self, **kwargs):

485

super().__init__('custom_page', **kwargs)

486

487

def create_page_containers(self, page):

488

"""Create custom container layout."""

489

# Main content area

490

content_container = DownExpandingContainer(

491

'content',

492

parent=page,

493

left=self.left_margin,

494

top=self.top_margin,

495

width=self.body_width

496

)

497

498

# Sidebar container

499

sidebar_container = DownExpandingContainer(

500

'sidebar',

501

parent=page,

502

left=self.left_margin + self.body_width + 10*MM,

503

top=self.top_margin,

504

width=40*MM

505

)

506

507

return {

508

'content': content_container,

509

'sidebar': sidebar_container

510

}

511

```

512

513

### Template Error Handling

514

515

```python

516

from rinohtype.template import TemplateConfigurationError, PageLayoutError

517

518

def safe_template_creation():

519

"""Create template with error handling."""

520

try:

521

template = CustomTemplate()

522

return template

523

except TemplateConfigurationError as e:

524

print(f"Template configuration error: {e}")

525

# Fall back to default template

526

return Article()

527

except PageLayoutError as e:

528

print(f"Page layout error: {e}")

529

return None

530

531

def validate_template_options(template, **options):

532

"""Validate template options before use."""

533

for name, value in options.items():

534

if not hasattr(template, name):

535

raise TemplateConfigurationError(f"Unknown option: {name}")

536

537

option = getattr(template.__class__, name)

538

if hasattr(option, 'validator') and option.validator:

539

if not option.validator(value):

540

raise TemplateConfigurationError(f"Invalid value for {name}: {value}")

541

```