readfile
引入外部文件
有时,某些内容适用于多个文档,或保存在一个本身并非文档的文件中。针对这类情况,readfile 短代码允许您将外部文件的内容导入到文档中。
复用文档
如果您希望在某些文档中复用部分内容,可以将该内容写在单独的文件中,并在需要的地方引入。
例如,假设您有一个名为 installation.md 的文件,其内容如下:
## Installation
{{% alert title="Note" color="primary" %}}
Check system compatibility before proceeding.
{{% /alert %}}
1. Download the installation files.
1. Run the installation script
`sudo sh install.sh`
1. Test that your installation was successfully completed.
您可以将此部分内容引入另一篇文档:
The following section explains how to install the database:
{{% readfile "installation.md" %}}
渲染效果就如同这些说明直接写在父文档中一样。若导入的文件包含短代码,则需要 Hugo v0.101.0 及以上版本才能正确渲染。
The following section explains how to install the database:
Installation
Note
Check system compatibility before proceeding.
-
Download the installation files.
-
Run the installation script
sudo sh install.sh -
Test that your installation was successfully completed.
该参数为文件的相对路径。仅支持父文件工作目录下的相对路径。
对于当前工作目录之外的文件,可以使用以 / 开头的绝对路径。根目录为 /content 文件夹。
Include code files
假设您有一个 includes 文件夹,其中包含多个希望作为文档一部分使用的代码示例。您可以使用 readfile 并配合一些附加参数:
To create a new pipeline, follow the next steps:
1. Create a configuration file `config.yaml`:
{{< readfile file="includes/config.yaml" code="true" lang="yaml" >}}
1. Apply the file to your cluster `kubectl apply config.yaml`
此代码会自动读取 includes/config.yaml 的内容并将其插入文档。渲染后的文本显示如下:
To create a new pipeline, follow the next steps:
-
Create a configuration file
config.yaml:apiVersion: tekton.dev/v1beta1 kind: Task metadata: name: hello spec: steps: - name: echo image: alpine script: | #!/bin/sh echo "Hello World" -
Apply the file to your cluster
kubectl apply config.yaml
Warning
You must use{{< >}}
delimiters for the code highlighting to work correctly.
file 参数指定文件的相对路径。仅支持父文件工作目录下的相对路径。
对于当前工作目录之外的文件,可以使用以 / 开头的绝对路径,其根目录为 /content 文件夹。
| Parameter | Default | Description |
|---|---|---|
| file | Path of external file | |
| code | false | Boolean value. If true the contents is treated as code |
| lang | plain text | Programming language |
Error reporting
若短代码无法找到指定的文件,则会引发编译错误。
在以下示例中,如果 Hugo 无法找到 includes/deploy.yml 文件,便会抛出编译错误
{{< readfile file="includes/deploy.yaml" code="true" lang="yaml" >}}
或者,您可以选择在渲染页面上显示提示信息,而非直接引发编译错误。只需添加 draft="true" 参数即可,例如:
{{< readfile file="includes/deploy.yaml" code="true" lang="yaml" draft="true" >}}