or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

tessl/pypi-chevron

A fast, PEP8-compliant Python implementation of the Mustache templating language

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/chevron@0.14.x

To install, run

npx @tessl/cli install tessl/pypi-chevron@0.14.0

0

# Chevron

1

2

A fast, PEP8-compliant Python implementation of the Mustache templating language. Chevron provides logic-less template rendering with full spec compliance, running significantly faster than alternative implementations while supporting advanced features like partials, lambda functions, and variable scoping.

3

4

## Package Information

5

6

- **Package Name**: chevron

7

- **Language**: Python

8

- **Installation**: `pip install chevron`

9

10

## Core Imports

11

12

```python

13

import chevron

14

```

15

16

For command-line usage:

17

```bash

18

chevron template.mustache -d data.json

19

```

20

21

## Basic Usage

22

23

```python

24

import chevron

25

26

# Basic string templating

27

result = chevron.render('Hello, {{ name }}!', {'name': 'World'})

28

print(result) # "Hello, World!"

29

30

# File-based templating

31

with open('template.mustache', 'r') as template_file:

32

result = chevron.render(template_file, {'name': 'World'})

33

34

# Using partials (template includes)

35

result = chevron.render(

36

'Hello, {{> greeting }}!',

37

{'name': 'World'},

38

partials_dict={'greeting': '{{ name }}'}

39

)

40

41

# File-based template with JSON data

42

result = chevron.main('template.mustache', 'data.json')

43

44

# File-based template with YAML data (requires PyYAML)

45

result = chevron.main('template.mustache', 'data.yaml', yaml_loader='SafeLoader')

46

```

47

48

## Architecture

49

50

Chevron uses a two-stage rendering process:

51

52

- **Tokenizer**: Parses Mustache templates into a stream of tokens (literals, variables, sections, partials, etc.)

53

- **Renderer**: Processes tokens against data context, handling scoping, conditionals, iterations, and output generation

54

55

This separation enables efficient template caching, custom delimiter support, and robust error handling while maintaining full Mustache specification compliance.

56

57

## Capabilities

58

59

### Template Rendering

60

61

The core template rendering functionality that processes Mustache templates with data context, supporting all Mustache specification features including variables, sections, inverted sections, comments, partials, and custom delimiters.

62

63

```python { .api }

64

def render(template='', data={}, partials_path='.', partials_ext='mustache',

65

partials_dict={}, padding='', def_ldel='{{', def_rdel='}}',

66

scopes=None, warn=False, keep=False):

67

"""

68

Render a mustache template.

69

70

Parameters:

71

- template: str or file-like object, the mustache template

72

- data: dict, python dictionary with your data scope (default: {})

73

- partials_path: str, path to directory containing partials (default: '.')

74

- partials_ext: str, extension for partial files (default: 'mustache')

75

- partials_dict: dict, dictionary of partials (default: {})

76

- padding: str, internal padding parameter (default: '')

77

- def_ldel: str, default left delimiter (default: '{{')

78

- def_rdel: str, default right delimiter (default: '}}')

79

- scopes: list, list of scopes for key lookup (default: None)

80

- warn: bool, issue warnings for missing keys to stderr (default: False)

81

- keep: bool, keep unreplaced tags when keys not found (default: False)

82

83

Returns:

84

str: Rendered template as string

85

"""

86

```

87

88

### File-Based Template Processing

89

90

High-level convenience function for rendering templates from files with optional JSON/YAML data files, providing automatic file handling and data loading.

91

92

```python { .api }

93

def main(template, data=None, yaml_loader='SafeLoader', **kwargs):

94

"""

95

Render mustache template from file paths.

96

97

Parameters:

98

- template: str, path to mustache template file

99

- data: str or None, path to JSON/YAML data file (optional)

100

- yaml_loader: str, YAML loader class name when PyYAML is available (default: 'SafeLoader')

101

- **kwargs: additional arguments passed to render()

102

103

Returns:

104

str: Rendered template as string

105

"""

106

```

107

108

### Command-Line Interface

109

110

Entry point for command-line template rendering with argument parsing and error handling, supporting all rendering options through command-line flags.

111

112

```python { .api }

113

def cli_main():

114

"""

115

Command-line interface entry point.

116

117

Processes command-line arguments and renders templates to stdout.

118

Supports template files, data files, partials configuration,

119

custom delimiters, and warning options.

120

121

Parameters:

122

None (uses sys.argv for command-line arguments)

123

124

Returns:

125

None (outputs to stdout, exits on error)

126

"""

127

```

128

129

130

## Types

131

132

```python { .api }

133

class ChevronError(SyntaxError):

134

"""

135

Custom exception for Chevron-specific template syntax errors.

136

137

Raised when template parsing encounters syntax errors such as:

138

- Unclosed tags

139

- Mismatched section start/end tags

140

- Invalid delimiter syntax

141

- Unexpected end of file

142

"""

143

```

144

145

## Advanced Usage Examples

146

147

### Partials (Template Includes)

148

149

```python

150

import chevron

151

152

# Dictionary-based partials

153

template = 'Hello, {{> greeting }}!'

154

data = {'name': 'World'}

155

partials = {'greeting': '{{ name }}'}

156

157

result = chevron.render(template, data, partials_dict=partials)

158

# Output: "Hello, World!"

159

160

# File-based partials

161

# Assuming ./partials/header.mustache contains "Welcome, {{ name }}!"

162

template = '{{> header }} How are you?'

163

result = chevron.render(

164

template,

165

{'name': 'Alice'},

166

partials_path='./partials',

167

partials_ext='mustache'

168

)

169

# Output: "Welcome, Alice! How are you?"

170

```

171

172

### Lambda Functions

173

174

```python

175

import chevron

176

177

def upper_case(text, render):

178

"""Convert rendered text to uppercase"""

179

return render(text).upper()

180

181

def bold(text, render):

182

"""Wrap rendered text in HTML bold tags"""

183

return '<b>' + render(text) + '</b>'

184

185

template = '{{# upper }} Hello {{ name }} {{/ upper }} and {{# bold }} {{ greeting }} {{/ bold }}'

186

data = {

187

'name': 'world',

188

'greeting': 'welcome',

189

'upper': upper_case,

190

'bold': bold

191

}

192

193

result = chevron.render(template, data)

194

# Output: "HELLO WORLD and <b>welcome</b>"

195

```

196

197

### Custom Delimiters

198

199

```python

200

import chevron

201

202

# Use different delimiters to avoid conflicts

203

template = 'Hello, <% name %>! Cost: ${{ price }} (<%{ unescaped }%>)'

204

data = {'name': 'Alice', 'price': '10.00', 'unescaped': '<script>'}

205

206

result = chevron.render(template, data, def_ldel='<%', def_rdel='%>')

207

# Output: "Hello, Alice! Cost: $10.00 (<script>)"

208

```

209

210

### Error Handling

211

212

```python

213

import chevron

214

215

try:

216

result = chevron.render('{{# section }} unclosed section', {})

217

except chevron.ChevronError as e:

218

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

219

# Output: "Template error: Unexpected EOF..."

220

221

# Warning mode for missing keys

222

template = 'Hello {{ name }} and {{ missing_key }}!'

223

result = chevron.render(template, {'name': 'World'}, warn=True)

224

# Prints warning to stderr: "Could not find key 'missing_key'"

225

# Output: "Hello World and !"

226

227

# Keep mode preserves unreplaced tags

228

result = chevron.render(template, {'name': 'World'}, keep=True)

229

# Output: "Hello World and {{ missing_key }}!"

230

```