Embedding files
Put files inside the executable.
On this page
#embed and #embed_dir read files while compiling and put their contents in the executable, so the program ships as one file.
Embed one file#
#embed("path") gives the file's contents as a String. The path is relative to the project's valk.json:
Valk
fn not_found_page() String {
return #embed("views/404.html")
}
fn main() {
let page = not_found_page()
println(page.bytes > 0) // true
}
Each #embed puts its own copy in the executable. When several places need the same file, embed it once in a function, as above, and call that.
Embed a directory#
#embed_dir("path") reads a directory recursively and gives a Map[String] from each file's relative path to its contents:
Valk
fn main() {
let views = #embed_dir("views")
each views as content, name {
println("%name: %{content.bytes} bytes") // 404.html: 249 bytes, ...
}
let page = views.get("404.html") !? ""
println(page.bytes > 0) // true
}
Files in subdirectories use / in their name, such as blog/post.html.
Things to know#
- The path must be a string literal, and the file must exist when you build.
- Changing an embedded file needs a rebuild.
- A typical use is shipping templates or static web assets with a server.
