or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

asset-management.mdbackground-callbacks.mdcallback-system.mdcomponent-libraries.mdcore-application.mdindex.mdmulti-page-apps.mdspecial-values.md

asset-management.mddocs/

0

# Asset Management

1

2

Dash provides comprehensive asset management for static files, external resources, and URL generation. Assets include CSS stylesheets, JavaScript files, images, and other static resources.

3

4

## Capabilities

5

6

### Asset URL Generation

7

8

Generate URLs for static assets with automatic fingerprinting and cache busting.

9

10

```python { .api }

11

def get_asset_url(path: str) -> str:

12

"""

13

Generate URL for asset file in the assets folder.

14

15

Parameters:

16

- path: Relative path to asset file within assets folder

17

18

Returns:

19

- Full URL to the asset with cache-busting parameters

20

"""

21

```

22

23

### Path Utilities

24

25

Handle URL paths and routing within Dash applications.

26

27

```python { .api }

28

def get_relative_path(path: str) -> str:

29

"""

30

Get relative path from the current request.

31

32

Parameters:

33

- path: Full or absolute path

34

35

Returns:

36

- Relative path from application root

37

"""

38

39

def strip_relative_path(path: str) -> str:

40

"""

41

Remove relative path prefix from URL.

42

43

Parameters:

44

- path: Path with potential relative prefix

45

46

Returns:

47

- Path with relative prefix removed

48

"""

49

```

50

51

### External Resources

52

53

Configure external CSS and JavaScript resources for the application.

54

55

```python { .api }

56

# External resource configuration

57

external_stylesheets = [

58

'https://codepen.io/chriddyp/pen/bWLwgP.css',

59

{

60

'href': 'https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css',

61

'rel': 'stylesheet',

62

'integrity': 'sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO',

63

'crossorigin': 'anonymous'

64

}

65

]

66

67

external_scripts = [

68

'https://code.jquery.com/jquery-3.6.0.min.js',

69

{

70

'src': 'https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js',

71

'integrity': 'sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p',

72

'crossorigin': 'anonymous'

73

}

74

]

75

```

76

77

### Asset Loading

78

79

Automatic loading of assets from the assets folder with development hot reloading.

80

81

```python { .api }

82

# Asset folder configuration

83

app = Dash(

84

__name__,

85

assets_folder='assets', # Assets directory path

86

assets_url_path='/assets/', # URL path for assets

87

assets_ignore='.*ignored.*' # Regex pattern to ignore files

88

)

89

```

90

91

## Usage Examples

92

93

### Basic Asset Usage

94

95

**Project structure:**

96

```

97

app.py

98

assets/

99

├── style.css

100

├── script.js

101

├── logo.png

102

└── data/

103

└── sample.json

104

```

105

106

**app.py:**

107

```python

108

from dash import Dash, html, dcc

109

110

app = Dash(__name__)

111

112

app.layout = html.Div([

113

# CSS and JS automatically loaded from assets/

114

html.Img(src=app.get_asset_url('logo.png')),

115

html.H1("My Dash App"),

116

117

# Reference asset in component

118

html.Div(id="data-container"),

119

120

# Load data file

121

dcc.Store(

122

id='data-store',

123

data=app.get_asset_url('data/sample.json')

124

)

125

])

126

```

127

128

**assets/style.css:**

129

```css

130

/* Automatically loaded */

131

body {

132

font-family: Arial, sans-serif;

133

margin: 0;

134

padding: 20px;

135

}

136

137

#data-container {

138

background-color: #f0f0f0;

139

padding: 10px;

140

border-radius: 5px;

141

}

142

```

143

144

### External Resources

145

146

```python

147

from dash import Dash, html

148

149

# External resources

150

external_stylesheets = [

151

# CDN stylesheet

152

'https://codepen.io/chriddyp/pen/bWLwgP.css',

153

154

# Bootstrap with integrity checking

155

{

156

'href': 'https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css',

157

'rel': 'stylesheet',

158

'integrity': 'sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3',

159

'crossorigin': 'anonymous'

160

}

161

]

162

163

external_scripts = [

164

# jQuery

165

'https://code.jquery.com/jquery-3.6.0.min.js',

166

167

# Custom external script

168

{

169

'src': 'https://example.com/custom-script.js',

170

'defer': True

171

}

172

]

173

174

app = Dash(

175

__name__,

176

external_stylesheets=external_stylesheets,

177

external_scripts=external_scripts

178

)

179

180

app.layout = html.Div([

181

html.H1("App with External Resources", className="display-4"),

182

html.P("Bootstrap styling applied!", className="lead")

183

])

184

```

185

186

### Dynamic Asset Loading

187

188

```python

189

from dash import Dash, html, dcc, callback, Input, Output

190

import json

191

import os

192

193

app = Dash(__name__)

194

195

app.layout = html.Div([

196

dcc.Dropdown(

197

id='theme-selector',

198

options=[

199

{'label': 'Light Theme', 'value': 'light'},

200

{'label': 'Dark Theme', 'value': 'dark'},

201

{'label': 'Blue Theme', 'value': 'blue'}

202

],

203

value='light'

204

),

205

html.Div(id='dynamic-content')

206

])

207

208

@callback(

209

Output('dynamic-content', 'children'),

210

Input('theme-selector', 'value')

211

)

212

def load_theme_assets(theme):

213

# Load theme-specific data

214

data_file = f'assets/themes/{theme}-config.json'

215

216

if os.path.exists(data_file):

217

with open(data_file) as f:

218

theme_config = json.load(f)

219

else:

220

theme_config = {'name': theme, 'colors': {}}

221

222

return html.Div([

223

html.H2(f"{theme_config['name']} Theme Active"),

224

html.Img(src=app.get_asset_url(f'themes/{theme}-logo.png')),

225

html.Link(

226

rel='stylesheet',

227

href=app.get_asset_url(f'themes/{theme}.css')

228

)

229

])

230

```

231

232

### Asset Fingerprinting

233

234

```python

235

from dash import Dash, html

236

237

app = Dash(__name__)

238

239

# Enable asset fingerprinting for production

240

app.config.update({

241

'compress': True, # Enable gzip compression

242

'serve_locally': True # Serve assets locally vs CDN

243

})

244

245

app.layout = html.Div([

246

# Assets get fingerprinted URLs like: /assets/style.css?v=1.0.0

247

html.Img(src=app.get_asset_url('logo.png')),

248

249

# Multiple asset references

250

html.Div([

251

html.Img(src=app.get_asset_url('icons/home.svg')),

252

html.Img(src=app.get_asset_url('icons/user.svg')),

253

html.Img(src=app.get_asset_url('icons/settings.svg'))

254

])

255

])

256

```

257

258

### Asset Preprocessing

259

260

**Using SASS preprocessing:**

261

262

**assets/style.scss:**

263

```scss

264

$primary-color: #007bff;

265

$secondary-color: #6c757d;

266

267

.dashboard {

268

.header {

269

background-color: $primary-color;

270

padding: 1rem;

271

272

h1 {

273

color: white;

274

margin: 0;

275

}

276

}

277

278

.content {

279

padding: 2rem;

280

background-color: lighten($secondary-color, 40%);

281

}

282

}

283

```

284

285

**app.py:**

286

```python

287

from dash import Dash, html

288

289

# SASS files automatically compiled to CSS in assets/

290

app = Dash(__name__)

291

292

app.layout = html.Div([

293

html.Div([

294

html.H1("Dashboard")

295

], className="header"),

296

297

html.Div([

298

html.P("Dashboard content here...")

299

], className="content")

300

], className="dashboard")

301

```

302

303

### Custom Asset Handling

304

305

```python

306

from dash import Dash, html

307

import os

308

309

class CustomDash(Dash):

310

def get_asset_url(self, path):

311

# Custom asset URL logic

312

if path.startswith('images/'):

313

# Serve images from CDN

314

return f"https://cdn.example.com/{path}"

315

elif path.endswith('.css'):

316

# Add version parameter to CSS files

317

version = os.path.getmtime(f"assets/{path}")

318

return f"/assets/{path}?v={version}"

319

else:

320

# Default behavior

321

return super().get_asset_url(path)

322

323

app = CustomDash(__name__)

324

325

app.layout = html.Div([

326

html.Img(src=app.get_asset_url('images/banner.jpg')), # From CDN

327

# CSS will have version parameter

328

])

329

```

330

331

### Multi-Page Asset Organization

332

333

**Project structure:**

334

```

335

app.py

336

assets/

337

├── global.css

338

├── components/

339

│ ├── navbar.css

340

│ └── footer.css

341

└── pages/

342

├── home.css

343

├── analytics.css

344

└── settings.css

345

```

346

347

**pages/analytics.py:**

348

```python

349

import dash

350

from dash import html, dcc

351

352

dash.register_page(__name__, path='/analytics')

353

354

def layout():

355

return html.Div([

356

# Page-specific styling automatically loaded

357

html.Link(

358

rel='stylesheet',

359

href=dash.get_asset_url('pages/analytics.css')

360

),

361

362

html.H1("Analytics Dashboard"),

363

# Page content...

364

])

365

```

366

367

## Types

368

369

```python { .api }

370

AssetPath = str # Path to asset file

371

AssetURL = str # Generated asset URL

372

ExternalResource = Union[str, Dict[str, str]] # External resource specification

373

ResourceList = List[ExternalResource] # List of external resources

374

```