or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

client-compilation.mdcompilation.mdconfiguration.mdexpress-integration.mdindex.mdrendering.md

rendering.mddocs/

0

# Template Rendering

1

2

Direct template-to-HTML conversion for simple use cases and development environments. These functions combine compilation and execution in a single step, making them ideal for one-time rendering or prototyping.

3

4

## Capabilities

5

6

### Render Function

7

8

Renders a Pug template string directly to HTML without explicitly creating a template function.

9

10

```javascript { .api }

11

/**

12

* Render a Pug template string directly to HTML

13

* @param str - Pug template source code

14

* @param options - Rendering options including locals

15

* @param fn - Optional callback for async operation

16

* @returns HTML string (sync) or calls callback (async)

17

*/

18

function render(str, options, fn);

19

```

20

21

**Usage Examples:**

22

23

```javascript

24

const pug = require('pug');

25

26

// Basic rendering

27

const html = pug.render('p Hello #{name}!', { name: 'World' });

28

// Result: <p>Hello World!</p>

29

30

// With template options

31

const html2 = pug.render(`

32

doctype html

33

html

34

head

35

title= title

36

body

37

h1= heading

38

if users

39

ul

40

each user in users

41

li= user.name

42

`, {

43

title: 'User List',

44

heading: 'All Users',

45

users: [

46

{ name: 'Alice' },

47

{ name: 'Bob' },

48

{ name: 'Charlie' }

49

],

50

pretty: true

51

});

52

53

// Async rendering with callback

54

pug.render('p Processing...', {}, function(err, html) {

55

if (err) {

56

console.error('Rendering error:', err);

57

} else {

58

console.log('Rendered:', html);

59

}

60

});

61

```

62

63

### Render File Function

64

65

Renders a Pug template file directly to HTML.

66

67

```javascript { .api }

68

/**

69

* Render a Pug template file directly to HTML

70

* @param path - Path to Pug template file

71

* @param options - Rendering options including locals

72

* @param fn - Optional callback for async operation

73

* @returns HTML string (sync) or calls callback (async)

74

*/

75

function renderFile(path, options, fn);

76

```

77

78

**Usage Examples:**

79

80

```javascript

81

const pug = require('pug');

82

83

// Render from file

84

const html = pug.renderFile('./views/user-profile.pug', {

85

user: {

86

name: 'Alice Smith',

87

email: 'alice@example.com',

88

avatar: '/images/alice.jpg'

89

},

90

isLoggedIn: true

91

});

92

93

// With caching for performance

94

const html2 = pug.renderFile('./views/dashboard.pug', {

95

cache: true,

96

filename: './views/dashboard.pug', // Required for caching

97

user: { name: 'Bob' },

98

stats: { posts: 42, followers: 156 }

99

});

100

101

// Async rendering

102

pug.renderFile('./views/email-template.pug', {

103

recipient: 'user@example.com',

104

subject: 'Welcome!'

105

}, function(err, html) {

106

if (err) {

107

console.error('Template error:', err);

108

} else {

109

// Send email with rendered HTML

110

sendEmail(html);

111

}

112

});

113

```

114

115

### Rendering Options

116

117

Rendering functions accept all compilation options plus template locals:

118

119

```javascript { .api }

120

interface RenderingOptions extends CompilationOptions {

121

/** Enable template caching (requires filename for file-based rendering) */

122

cache?: boolean;

123

/** Template variables - any additional properties become template locals */

124

[localName: string]: any;

125

}

126

```

127

128

### Callback Interface

129

130

For async operations, callbacks follow the standard Node.js error-first pattern:

131

132

```javascript { .api }

133

/**

134

* Callback function for async rendering operations

135

* @param err - Error object if rendering failed, null if successful

136

* @param html - Rendered HTML string if successful

137

*/

138

type RenderCallback = (err: Error | null, html?: string) => void;

139

```

140

141

### Advanced Usage

142

143

**Template with Includes:**

144

145

```javascript

146

// views/layout.pug

147

const html = pug.renderFile('./views/page.pug', {

148

basedir: './views',

149

title: 'My Page',

150

content: 'Hello World'

151

});

152

153

// The template can use: include header.pug, include footer.pug

154

```

155

156

**Dynamic Template Selection:**

157

158

```javascript

159

function renderTemplate(templateName, data) {

160

const templatePath = `./views/${templateName}.pug`;

161

return pug.renderFile(templatePath, {

162

...data,

163

basedir: './views',

164

cache: process.env.NODE_ENV === 'production'

165

});

166

}

167

168

const html = renderTemplate('user-card', { user: userData });

169

```

170

171

**Conditional Rendering:**

172

173

```javascript

174

const html = pug.render(`

175

div.notification(class=type)

176

if type === 'error'

177

i.icon-error

178

else if type === 'warning'

179

i.icon-warning

180

else

181

i.icon-info

182

p= message

183

`, {

184

type: 'error',

185

message: 'Something went wrong!'

186

});

187

```

188

189

**Loop Rendering:**

190

191

```javascript

192

const html = pug.render(`

193

table

194

thead

195

tr

196

th Name

197

th Email

198

th Status

199

tbody

200

each user in users

201

tr(class=user.active ? 'active' : 'inactive')

202

td= user.name

203

td= user.email

204

td= user.active ? 'Active' : 'Inactive'

205

`, {

206

users: [

207

{ name: 'Alice', email: 'alice@example.com', active: true },

208

{ name: 'Bob', email: 'bob@example.com', active: false }

209

]

210

});

211

```

212

213

### Error Handling

214

215

Both rendering functions can throw errors or pass errors to callbacks:

216

217

```javascript

218

// Synchronous error handling

219

try {

220

const html = pug.render('invalid syntax {{}}');

221

} catch (err) {

222

console.error('Rendering failed:', err.message);

223

}

224

225

// Asynchronous error handling

226

pug.render('p Hello', {}, function(err, html) {

227

if (err) {

228

console.error('Async rendering failed:', err.message);

229

return;

230

}

231

console.log('Success:', html);

232

});

233

234

// File not found errors

235

try {

236

const html = pug.renderFile('./non-existent.pug', {});

237

} catch (err) {

238

console.error('File error:', err.code); // ENOENT

239

}

240

```

241

242

### Performance Considerations

243

244

- **Use `renderFile` with caching** for production applications

245

- **Use `render`** for dynamic templates or development

246

- **Consider `compile` + template function** for templates rendered multiple times

247

- **Set `compileDebug: false`** in production for better performance

248

249

```javascript

250

// Production rendering setup

251

const isProduction = process.env.NODE_ENV === 'production';

252

253

const html = pug.renderFile('./views/app.pug', {

254

cache: isProduction,

255

compileDebug: !isProduction,

256

pretty: !isProduction,

257

// ... template data

258

});

259

```