The webinclude
preprocessor works similar to the built-in
include
link which inserts (portions of) local files in a section within the book. The same
can be achieved with webinclude
however instead of specifying a path to the file
a URL can be used. The source of that URL is obtained an further processed like
with include
.
This preprocessor can be installed with Cargo:
cargo install mdbook-webinclude
Add the following line to your book.toml
file:
[preprocessor.webinclude]
Now you can use the webinclude
links in your book as described below.
Because the text is inserted before the book is rendered, Markdown from other sources can be included. This is especially useful when for instance your book lays in a different repository than the actual program.
Warning
Keep in mind that header levels remain the same and are not adapted to the current chapter's header level.
Text can be inserted as is as well which is less practical unless used within a code block. You can for example include source code from a different repository and wrap it in an appropiate code block.
Often you only need a specific part of the file, e.g. relevant lines for an example. Four different modes are supported for partial includes.
The first command only includes the second line from file. The second
command includes all lines up to line 10, i.e. the lines from 11 till the end of
the file are omitted. The third command includes all lines from line 2, i.e. the
first line is omitted. The last command includes the excerpt of document.md
consisting of lines 2 to 10.
To avoid breaking your book when modifying included files, you can also
include a specific section using anchors instead of line numbers.
An anchor is a pair of matching lines. The line beginning an anchor must
match the regex ANCHOR:\s*[\w_-]+
and similarly the ending line must match
the regex ANCHOR_END:\s*[\w_-]+
. This allows you to put anchors in
any kind of commented line.
Consider the following file to include:
/* ANCHOR: all */
// ANCHOR: component
struct Paddle {
hello: f32,
}
// ANCHOR_END: component
////////// ANCHOR: system
impl System for MySystem { ... }
////////// ANCHOR_END: system
/* ANCHOR_END: all */
Then in the book, all you have to do is:
For the really uncommon case where you want to literally include
{{#webinclude ...}}
simply prefix it with a backslash (\
).
HTTP headers can be configured in the book.toml
file.
Change this line in your book.toml
file:
- [preprocessor.webinclude]
+ [preprocessor.webinclude.headers]
You can then set the headers as described below.
[preprocessor.webinclude.headers]
user-agent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9; rv:50.0) Gecko/20100101 Firefox/50.0"
accept = "text/plain"