Managing assets
Poet comes with an asset management system that is deeply integrated with esbuild. That makes it easy to add and render different types of assets in your project. It also generates preload tags for imported resources.
context.assets.add()
The context.assets.add()
function allows you to add assets to your shortcode files. Its most common use case is to add CSS and JS to your layouts. When you use this function, Poet handles asset optimization by:
Adding preload tags for imported resources like fonts, images in CSS files, and imported scripts to prevent loading waterfalls
Appending cache-busting hashes to asset URLs to ensure browsers load the latest version when files change
Here's a practical example of how to use it in your layout file:
fn template(context, props, content) {
context.assets.add("resources/css/layout-minimal.css");
component {
{context.front_matter.title}
{context.assets.render()}
{content}
}
}
context.assets.render()
This function takes all assets added with context.assets.add()
and renders them in the appropriate place of your HTML document. In the example above, we placed it in the <head>
section of our layout file.
Using context.assets.add()
and context.assets.render()
functions as presented in the above example results in the assets rendered in the <head>
of the HTML document as follows (the layout-minimal.css in the above example imports some fonts):
context.assets.file()
The context.assets.file()
function takes a file name as an argument and then returns the file path. The most common use case for this function is to render images and other files in your content, for example: