本文翻译自How to check if a Hugo site is in development or production

有时我们希望能在使用Hugo的时候基于开发环境或生产环境展示不同的内容,在之前我使用过$.Site.IsServer来检查是否运行于开发服务器,不过其无法实现在开发环境查看生产环境的显示样式。

检查环境

实际上Hugo有一系列的方式来区分生产环境和开发环境,不过Hugo文档中关于如何区分它们的说明不太友好。

下述代码展示了在Hugo中检测环境的两种方式:

{{ hugo.Environment }} returns "development" or "production"
{{ hugo.IsProduction }} returns true or false

当使用hugo server在本地开发时,默认被设置为development,当使用hugo来构建站点时,默认被设置为production

基于环境动态展示

若想实现根据环境动态展示,可使用下述代码中的几种方法之一:

{{ if eq hugo.Environment "development" }}
  I render when in development
{{ end }}

{{ if eq hugo.Environment "production" }}
  I render when in production
{{ end }}

{{ if hugo.IsProduction }}
  I render when in production
{{ end }}

{{ if not hugo.IsProduction }}
  I render when <strong>not</strong> in production, which means
  I would render if the environment were manually set to "test"
{{ end }}

手工设置环境变量

若要在编写博文时将环境设置为production,可使用下述命令启动Hugo服务器:

# 短命令
hugo server -e production

# 长命令
hugo server --environment production

也可通过设置系统环境变量来实现:

HUGO_ENVIRONMENT=production hugo server

Hugo要求能改变其配置的环境变量必须以HUGO_前缀开头,可在Hugo环境变量说明中了解具体信息。

如果我们想在构建时将环境变量设置为除了production之外的其它值,可使用下述几种方法之一,在这些方法中,我们将环境变量设置为development,也可设置为我们期望的其它任何值。

hugo -e development
hugo --environment development
HUGO_ENVIRONMENT=development hugo

希望此文能帮助你来构建自己的Hugo站点,喜欢此文章的话可以的点赞或评论!