I tried using the new bundle feature (Bundle export by laurmaedje · Pull Request #7964 · typst/typst · GitHub), but the loading of assets isn’t very convenient.
I currently use the following code to insert images on my site:
// template.typ
#let image(src, width: none, height: none, ..attrs) = {
if (width == none and height == none) {
html.elem("img", attrs: (src: src, ..attrs.named()))
} else {
if (width == none and height != none) {
width = "auto"
} else if (width != none and height == none) {
height = "auto"
}
html.elem("img", attrs: (src: src, width: str(width), height: str(height),
..attrs.named()))
}
}
// blog/index.typ
#import "template.typ"
#image("./image.png", height: 500, width: 500)
This works fine when compiling the standalone file. I use make to compile all the pages and copy the assets to the output directory.
I wanted to update my code to use the bundle feature, so I created a new file
// site.typ
#document("/blog/index.html", include("/blog/index.typ"))
And tried to modify the image function to automatically export the image.
// template.typ
#let image(src, width: none, height: none, ..attrs) = {
asset(src, read(src, encoding: none))
if ...
// The rest is unchanged
}
However, this fails in multiple ways:
- File not found (searched at /home/…/image.png)
read is trying to load the file with a path relative to template.typ and not blog/index.typ. This is unexpected, I think it would make more sense if the paths were resolved relative to the file being compiled, at least as an option. A better option would be to make paths their own object (being resolved at construction) rather than normal strings. I can ignore this error by using absolute paths everywhere. - Error: assets are only supported in the bundle target
Even though I invoked typst with the--format bundleoption, this isn’t passed down to the individual documents.
Both limitations “make sense”, but they make it more difficult than necessary to export multi-file documents (html pages). I haven’t written it yet, but I think a workaround could be:
- Include metadata in the image function, instead of directly calling
asset - From the top level site.typ, loop through the metadata
- For each asset, determine the “owner” file (is that possible?) to generate the absolute path to copy.