Assets
Assets in Finch are JavaScript and CSS files that are injected into page templates dynamically. Instead of hardcoding <script> and <link> tags in every template, controllers register assets for the current request. The template then outputs them all at once using a single placeholder.
This is useful for page-specific scripts and styles: a page that uses a data table library only loads that library's JS/CSS when it is actually needed.
How It Works
- A controller calls
rq.addAsset()to register one or more assets for the current response. - The Jinja template calls
{{ assets.js() }}and{{ assets.css() }}to output the registered tags. - Finch renders the correct
<script>or<link>tags at those positions.
Adding Assets
Assets are added inside a controller method, just before rendering the view:
Future<String> showPage() async {
// Add a single JavaScript file
rq.addAsset(Asset(
path: '/public/js/datatable.min.js',
type: AssetType.js,
));
// Add a CSS file
rq.addAsset(Asset(
path: '/public/css/datatable.min.css',
type: AssetType.css,
));
return rq.renderView(path: 'pages/books');
}
To add multiple assets at once, use rq.addAssets():
rq.addAssets([
Asset(path: '/public/js/chart.js', type: AssetType.js),
Asset(path: '/public/css/chart.css', type: AssetType.css),
Asset(path: '/public/js/utils.js', type: AssetType.js),
]);
AssetType Values
| Value | Output |
|---|---|
AssetType.js |
<script src="path"></script> |
AssetType.css |
<link rel="stylesheet" href="path"> |
Outputting Assets in Templates
Place the asset placeholders in your base layout template. CSS should go inside <head> so it loads before the page renders. JavaScript should go just before </body> to avoid blocking page load:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>{{ $t('logo.title') }}</title>
<!-- Outputs all registered CSS <link> tags -->
{{ assets.css() }}
</head>
<body>
{% block content %}{% endblock %}
<!-- Outputs all registered JS <script> tags -->
{{ assets.js() }}
</body>
</html>
If no assets of a particular type have been registered, the placeholder renders as an empty string.
Serving Static Files
Assets are static files served from your publicDir. Configure the public directory in FinchConfigs:
FinchConfigs configs = FinchConfigs(
publicDir: pathTo(env['PUBLIC_DIR'] ?? './public'),
);
All files inside publicDir are accessible directly via their path. For example, a file at ./public/js/app.js is served at /public/js/app.js.
The
publicDirpath must be absolute. UsepathTo()to resolve it relative to the project root.
Result
The result of the above code will be a HTML page with the following content:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="/path/to/your/asset.css" />
</head>
<body>
<script src="/path/to/your/asset.js"></script>
Hello World
</body>
</html>