or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

admin.mdauth.mdcontrib.mddatabase-orm.mdforms.mdhttp.mdindex.mdmigrations.mdmypy-plugin.mdsignals.mdtemplates.mdtransactions.mdurls.mdviews.md

templates.mddocs/

0

# Template System

1

2

Django's template system provides secure HTML generation with automatic escaping, template inheritance, custom tags and filters, and multiple template engine support.

3

4

## Capabilities

5

6

### Template Engine

7

8

Core template engine classes for loading and rendering templates.

9

10

```python { .api }

11

class Engine:

12

"""

13

Template engine for loading and rendering templates.

14

15

Main interface for template operations with configurable backends.

16

"""

17

def __init__(self, dirs: list = None, app_dirs: bool = False, context_processors: list = None,

18

debug: bool = False, loaders: list = None, string_if_invalid: str = '',

19

file_charset: str = 'utf-8', libraries: dict = None, builtins: list = None,

20

autoescape: bool = True): ...

21

22

def from_string(self, template_code: str) -> Template: ...

23

def get_template(self, template_name: str) -> Template: ...

24

def select_template(self, template_name_list: list) -> Template: ...

25

def render_to_string(self, template_name: str, context: dict = None, request: HttpRequest = None) -> str: ...

26

27

engines: dict # Template engines registry

28

```

29

30

### Template Classes

31

32

Template objects for rendering content with context data.

33

34

```python { .api }

35

class Template:

36

"""

37

Compiled template ready for rendering.

38

39

Contains parsed template nodes and rendering methods.

40

"""

41

def __init__(self, template_string: str, origin=None, name: str = None, engine=None): ...

42

43

def render(self, context: Context = None) -> str: ...

44

def get_exception_info(self, exception: Exception, token) -> dict: ...

45

46

name: str

47

origin: Origin

48

engine: Engine

49

source: str

50

nodelist: NodeList

51

52

class Origin:

53

"""

54

Template origin information for debugging and caching.

55

"""

56

def __init__(self, name: str, template_name: str = None, loader=None): ...

57

58

name: str

59

template_name: str

60

loader: BaseLoader

61

```

62

63

### Context System

64

65

Context classes for providing data to templates during rendering.

66

67

```python { .api }

68

class Context(dict):

69

"""

70

Template context for variable resolution.

71

72

Stack-based context supporting nested scopes and context processors.

73

"""

74

def __init__(self, dict_: dict = None, autoescape: bool = True, use_l10n: bool = None, use_tz: bool = None): ...

75

76

def bind_template(self, template: Template) -> Context: ...

77

def __enter__(self) -> Context: ...

78

def __exit__(self, exc_type, exc_value, traceback) -> None: ...

79

def push(self, other: dict = None) -> dict: ...

80

def pop(self) -> dict: ...

81

def __setitem__(self, key: str, value) -> None: ...

82

def __getitem__(self, key: str): ...

83

def __delitem__(self, key: str) -> None: ...

84

def __contains__(self, key: str) -> bool: ...

85

def get(self, key: str, otherwise=None): ...

86

def setdefault(self, key: str, default=None): ...

87

def new(self, values: dict = None) -> Context: ...

88

def flatten(self) -> dict: ...

89

90

template: Template

91

render_context: RenderContext

92

autoescape: bool

93

use_l10n: bool

94

use_tz: bool

95

96

class RequestContext(Context):

97

"""

98

Context subclass that runs context processors automatically.

99

100

Integrates request object and applies configured context processors.

101

"""

102

def __init__(self, request: HttpRequest, dict_: dict = None, processors: list = None,

103

use_l10n: bool = None, use_tz: bool = None, autoescape: bool = True): ...

104

105

request: HttpRequest

106

107

class RenderContext(dict):

108

"""

109

Stack-based context for template rendering state.

110

"""

111

def __init__(self, dict_: dict = None): ...

112

def __enter__(self) -> RenderContext: ...

113

def __exit__(self, exc_type, exc_value, traceback) -> None: ...

114

def push_state(self, engine: Engine, **kwargs) -> None: ...

115

def pop_state(self) -> None: ...

116

```

117

118

### Template Nodes

119

120

Node classes representing parsed template elements.

121

122

```python { .api }

123

class Node:

124

"""

125

Base class for template nodes.

126

127

Represents a single element in the compiled template tree.

128

"""

129

must_be_first: bool = False

130

child_nodelists: tuple = ()

131

132

def render(self, context: Context) -> str: ...

133

def __iter__(self): ...

134

def get_nodes_by_type(self, nodetype: type) -> list: ...

135

136

class NodeList(list):

137

"""

138

List container for template nodes with rendering support.

139

"""

140

def __init__(self, nodes: list = None): ...

141

def render(self, context: Context) -> str: ...

142

def get_nodes_by_type(self, nodetype: type) -> list: ...

143

144

class TextNode(Node):

145

"""

146

Node for literal text content.

147

"""

148

def __init__(self, s: str): ...

149

150

s: str

151

152

class VariableNode(Node):

153

"""

154

Node for template variable resolution and output.

155

"""

156

def __init__(self, filter_expression: FilterExpression): ...

157

158

filter_expression: FilterExpression

159

160

class CommentNode(Node):

161

"""

162

Node for template comments (not rendered).

163

"""

164

def __init__(self, comment_text: str = ''): ...

165

166

comment_text: str

167

168

class IfNode(Node):

169

"""

170

Node for conditional template logic.

171

"""

172

def __init__(self, conditions_nodelists: list): ...

173

174

conditions_nodelists: list

175

176

class ForNode(Node):

177

"""

178

Node for template loops.

179

"""

180

def __init__(self, loopvars: list, sequence: FilterExpression, is_reversed: bool,

181

nodelist_loop: NodeList, nodelist_empty: NodeList = None): ...

182

183

loopvars: list

184

sequence: FilterExpression

185

is_reversed: bool

186

nodelist_loop: NodeList

187

nodelist_empty: NodeList

188

189

class IncludeNode(Node):

190

"""

191

Node for including other templates.

192

"""

193

def __init__(self, template: FilterExpression, extra_context: dict = None,

194

isolated_context: bool = False): ...

195

```

196

197

### Variable Resolution

198

199

Classes for resolving template variables and applying filters.

200

201

```python { .api }

202

class Variable:

203

"""

204

Template variable with lookup and filtering support.

205

206

Resolves dotted variable names in template context.

207

"""

208

def __init__(self, var: str): ...

209

210

def resolve(self, context: Context): ...

211

def __repr__(self) -> str: ...

212

def __str__(self) -> str: ...

213

214

var: str

215

literal: Any

216

lookups: tuple

217

translate: bool

218

message_context: str

219

220

class FilterExpression:

221

"""

222

Expression combining variable lookup with filters.

223

224

Parses and applies template filters to variables.

225

"""

226

def __init__(self, token: str, parser): ...

227

228

def resolve(self, context: Context, ignore_failures: bool = False): ...

229

def args_check(name: str, func, provided: list) -> bool: ...

230

def __str__(self) -> str: ...

231

232

token: str

233

filters: list

234

var: Variable

235

236

class Parser:

237

"""

238

Template parser for processing template syntax.

239

"""

240

def __init__(self, tokens: list): ...

241

242

def parse(self, parse_until: list = None) -> NodeList: ...

243

def skip_past(self, endtag: str) -> None: ...

244

def extend_nodelist(self, nodelist: NodeList, node: Node, token) -> None: ...

245

def error(self, token, msg: str) -> None: ...

246

def invalid_block_tag(self, token, command: str, parse_until: list = None) -> None: ...

247

def unclosed_block_tag(self, parse_until: list) -> None: ...

248

def next_token(self): ...

249

def prepend_token(self, token) -> None: ...

250

def delete_first_token(self) -> None: ...

251

252

tokens: list

253

tags: dict

254

filters: dict

255

command_stack: list

256

```

257

258

### Template Tags and Filters

259

260

System for registering custom template tags and filters.

261

262

```python { .api }

263

class Library:

264

"""

265

Registry for custom template tags and filters.

266

267

Container for registering and organizing template extensions.

268

"""

269

def __init__(self): ...

270

271

def tag(self, name: str = None, compile_function=None): ...

272

def tag_function(self, func): ...

273

def filter(self, name: str = None, filter_func=None, expects_localtime: bool = False,

274

is_safe: bool = False, needs_autoescape: bool = False): ...

275

def filter_function(self, func): ...

276

def simple_tag(self, func=None, takes_context: bool = False, name: str = None): ...

277

def inclusion_tag(self, filename: str, func=None, takes_context: bool = False, name: str = None): ...

278

def assignment_tag(self, func=None, takes_context: bool = False, name: str = None): ...

279

280

tags: dict

281

filters: dict

282

283

def register_tag(library: str, tag: str): ...

284

def register_filter(library: str, filter_name: str): ...

285

```

286

287

### Template Loaders

288

289

Classes for loading templates from various sources.

290

291

```python { .api }

292

class BaseLoader:

293

"""

294

Base template loader class.

295

296

Abstract interface for loading templates from different sources.

297

"""

298

def __init__(self, engine: Engine): ...

299

300

def get_template(self, template_name: str, skip: list = None) -> Template: ...

301

def get_template_sources(self, template_name: str): ...

302

def load_template_source(self, template_name: str, template_dirs: list = None) -> tuple: ...

303

304

engine: Engine

305

306

class FileSystemLoader(BaseLoader):

307

"""

308

Load templates from filesystem directories.

309

"""

310

def __init__(self, engine: Engine, dirs: list = None): ...

311

312

class AppDirectoriesLoader(BaseLoader):

313

"""

314

Load templates from application directories.

315

"""

316

def __init__(self, engine: Engine, dirs: list = None): ...

317

318

class CachedLoader(BaseLoader):

319

"""

320

Wrapper loader that caches compiled templates.

321

"""

322

def __init__(self, engine: Engine, loaders: list): ...

323

324

class LocmemLoader(BaseLoader):

325

"""

326

Load templates from dictionary in local memory.

327

"""

328

def __init__(self, engine: Engine, templates_dict: dict): ...

329

```

330

331

### Template Response

332

333

Response classes that defer template rendering until response processing.

334

335

```python { .api }

336

class TemplateResponse(HttpResponse):

337

"""

338

HTTP response that renders template with context.

339

340

Deferred rendering allows middleware to modify context before rendering.

341

"""

342

def __init__(self, request: HttpRequest, template, context: dict = None,

343

content_type: str = None, status: int = None, charset: str = None, using: str = None): ...

344

345

def resolve_template(self, template) -> Template: ...

346

def resolve_context(self, context: dict) -> Context: ...

347

def render(self) -> TemplateResponse: ...

348

def add_post_render_callback(self, callback) -> None: ...

349

350

template_name: Any

351

context_data: dict

352

using: str

353

is_rendered: bool

354

post_render_callbacks: list

355

356

class SimpleTemplateResponse(HttpResponse):

357

"""

358

Template response without request context processors.

359

"""

360

def __init__(self, template, context: dict = None, content_type: str = None,

361

status: int = None, charset: str = None, using: str = None): ...

362

```

363

364

### Context Processors

365

366

Functions that add variables to template context automatically.

367

368

```python { .api }

369

def debug(request: HttpRequest) -> dict:

370

"""

371

Add debug and SQL query information to context.

372

373

Args:

374

request: HTTP request object

375

376

Returns:

377

Dictionary with debug and sql_queries keys

378

"""

379

380

def request(request: HttpRequest) -> dict:

381

"""

382

Add request object to template context.

383

384

Args:

385

request: HTTP request object

386

387

Returns:

388

Dictionary with request key

389

"""

390

391

def csrf(request: HttpRequest) -> dict:

392

"""

393

Add CSRF token to template context.

394

395

Args:

396

request: HTTP request object

397

398

Returns:

399

Dictionary with csrf_token key

400

"""

401

402

def static(request: HttpRequest) -> dict:

403

"""

404

Add static files URL to template context.

405

406

Args:

407

request: HTTP request object

408

409

Returns:

410

Dictionary with STATIC_URL key

411

"""

412

413

def media(request: HttpRequest) -> dict:

414

"""

415

Add media files URL to template context.

416

417

Args:

418

request: HTTP request object

419

420

Returns:

421

Dictionary with MEDIA_URL key

422

"""

423

424

def tz(request: HttpRequest) -> dict:

425

"""

426

Add timezone information to template context.

427

428

Args:

429

request: HTTP request object

430

431

Returns:

432

Dictionary with TIME_ZONE key

433

"""

434

435

def i18n(request: HttpRequest) -> dict:

436

"""

437

Add internationalization info to template context.

438

439

Args:

440

request: HTTP request object

441

442

Returns:

443

Dictionary with LANGUAGES and LANGUAGE_CODE keys

444

"""

445

```

446

447

### Built-in Template Tags

448

449

Core template tags provided by Django.

450

451

```python { .api }

452

# Control flow tags

453

def if_tag(parser: Parser, token) -> IfNode: ...

454

def for_tag(parser: Parser, token) -> ForNode: ...

455

def cycle_tag(parser: Parser, token) -> Node: ...

456

def firstof_tag(parser: Parser, token) -> Node: ...

457

def with_tag(parser: Parser, token) -> Node: ...

458

459

# Template inclusion tags

460

def include_tag(parser: Parser, token) -> IncludeNode: ...

461

def extends_tag(parser: Parser, token) -> Node: ...

462

def block_tag(parser: Parser, token) -> Node: ...

463

464

# URL tags

465

def url_tag(parser: Parser, token) -> Node: ...

466

467

# Loading tags

468

def load_tag(parser: Parser, token) -> Node: ...

469

470

# Comment tags

471

def comment_tag(parser: Parser, token) -> CommentNode: ...

472

473

# Spacing tags

474

def spaceless_tag(parser: Parser, token) -> Node: ...

475

def autoescape_tag(parser: Parser, token) -> Node: ...

476

477

# Variable assignment tags

478

def regroup_tag(parser: Parser, token) -> Node: ...

479

def templatetag_tag(parser: Parser, token) -> Node: ...

480

def widthratio_tag(parser: Parser, token) -> Node: ...

481

482

# Conditional assignment tags

483

def ifchanged_tag(parser: Parser, token) -> Node: ...

484

485

# Debugging tags

486

def debug_tag(parser: Parser, token) -> Node: ...

487

488

# Localization tags

489

def localize_tag(parser: Parser, token) -> Node: ...

490

def get_current_language_tag(parser: Parser, token) -> Node: ...

491

def get_language_info_tag(parser: Parser, token) -> Node: ...

492

def get_language_info_list_tag(parser: Parser, token) -> Node: ...

493

def language_tag(parser: Parser, token) -> Node: ...

494

def trans_tag(parser: Parser, token) -> Node: ...

495

def blocktrans_tag(parser: Parser, token) -> Node: ...

496

497

# Static files tags

498

def static_tag(parser: Parser, token) -> Node: ...

499

def get_static_prefix_tag(parser: Parser, token) -> Node: ...

500

def get_media_prefix_tag(parser: Parser, token) -> Node: ...

501

```

502

503

### Built-in Template Filters

504

505

Core template filters for data formatting and manipulation.

506

507

```python { .api }

508

# String filters

509

def add(value, arg) -> str: ...

510

def addslashes(value) -> str: ...

511

def capfirst(value) -> str: ...

512

def center(value, width: int) -> str: ...

513

def cut(value, arg: str) -> str: ...

514

def escape(value) -> str: ...

515

def escapejs(value) -> str: ...

516

def floatformat(value, arg: int = -1) -> str: ...

517

def force_escape(value) -> str: ...

518

def linebreaks(value) -> str: ...

519

def linebreaksbr(value) -> str: ...

520

def linenumbers(value) -> str: ...

521

def ljust(value, width: int) -> str: ...

522

def lower(value) -> str: ...

523

def make_list(value) -> list: ...

524

def rjust(value, width: int) -> str: ...

525

def safe(value) -> str: ...

526

def safeseq(value) -> list: ...

527

def slugify(value) -> str: ...

528

def stringformat(value, format_str: str) -> str: ...

529

def striptags(value) -> str: ...

530

def title(value) -> str: ...

531

def truncatechars(value, length: int) -> str: ...

532

def truncatechars_html(value, length: int) -> str: ...

533

def truncatewords(value, length: int) -> str: ...

534

def truncatewords_html(value, length: int) -> str: ...

535

def upper(value) -> str: ...

536

def urlencode(value) -> str: ...

537

def urlize(value) -> str: ...

538

def urlizetrunc(value, length: int) -> str: ...

539

def wordcount(value) -> int: ...

540

def wordwrap(value, width: int) -> str: ...

541

542

# Number filters

543

def divisibleby(value, arg: int) -> bool: ...

544

def floatformat(value, arg: int = -1) -> str: ...

545

546

# Date filters

547

def date(value, format_str: str = None) -> str: ...

548

def time(value, format_str: str = None) -> str: ...

549

def timesince(value, base_date=None) -> str: ...

550

def timeuntil(value, base_date=None) -> str: ...

551

552

# List filters

553

def dictsort(value, key: str) -> list: ...

554

def dictsortreversed(value, key: str) -> list: ...

555

def first(value): ...

556

def join(value, delimiter: str) -> str: ...

557

def last(value): ...

558

def length(value) -> int: ...

559

def length_is(value, length: int) -> bool: ...

560

def random(value): ...

561

def slice_filter(value, slice_str: str) -> list: ...

562

def unordered_list(value) -> str: ...

563

564

# Logic filters

565

def default(value, default_value): ...

566

def default_if_none(value, default_value): ...

567

def yesno(value, yes_no_maybe: str = None) -> str: ...

568

569

# File filters

570

def filesizeformat(value) -> str: ...

571

572

# Other filters

573

def pprint(value) -> str: ...

574

def phone2numeric(value) -> str: ...

575

def pluralize(value, suffix: str = 's') -> str: ...

576

def removetags(value, tags: str) -> str: ...

577

def iriencode(value) -> str: ...

578

def json_script(value, element_id: str) -> str: ...

579

```

580

581

### Template Exceptions

582

583

Exception classes for template processing errors.

584

585

```python { .api }

586

class TemplateDoesNotExist(Exception):

587

"""

588

Template file not found error.

589

590

Raised when requested template cannot be located by any loader.

591

"""

592

def __init__(self, msg: str, tried: list = None, backend=None, chain: list = None): ...

593

594

backend: Engine

595

tried: list

596

chain: list

597

598

class TemplateSyntaxError(Exception):

599

"""

600

Template syntax parsing error.

601

602

Raised when template contains invalid syntax or structure.

603

"""

604

def __init__(self, msg: str, tried: list = None, backend=None, chain: list = None): ...

605

606

class VariableDoesNotExist(Exception):

607

"""

608

Template variable resolution error.

609

610

Raised when template variable cannot be resolved in context.

611

"""

612

def __init__(self, msg: str, params: tuple = ()): ...

613

614

msg: str

615

params: tuple

616

```

617

618

### Template Utilities

619

620

Helper functions for template operations and debugging.

621

622

```python { .api }

623

def select_template(template_name_list: list, using: str = None) -> Template:

624

"""

625

Load template from list, using first that exists.

626

627

Args:

628

template_name_list: List of template names to try

629

using: Template engine name

630

631

Returns:

632

First existing template from list

633

"""

634

635

def get_template(template_name: str, using: str = None) -> Template:

636

"""

637

Load and return template by name.

638

639

Args:

640

template_name: Name of template to load

641

using: Template engine name

642

643

Returns:

644

Compiled template object

645

"""

646

647

def render_to_string(template_name: str, context: dict = None, request: HttpRequest = None, using: str = None) -> str:

648

"""

649

Render template to string with given context.

650

651

Args:

652

template_name: Template name to render

653

context: Template context data

654

request: HTTP request for RequestContext

655

using: Template engine name

656

657

Returns:

658

Rendered template as string

659

"""

660

661

def context_processors_list() -> list:

662

"""

663

Get list of configured context processors.

664

665

Returns:

666

List of context processor functions

667

"""

668

```