You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Hugo中合理组织内容,避免滥用layouts目录?

Hugo多区块页面的内容组织方案

针对你不想把所有内容硬塞进layouts目录的需求,这里有几个实用的落地方法:

1. Front Matter定义区块元数据 + Partial渲染

在content目录的页面md文件里,用Front Matter的数组配置每个区块的基础信息,把区块的结构逻辑放在layouts的partial里,内容通过参数传递。

比如首页的content/home/index.md:

---
title: "我的首页"
sections:
  - type: "hero"
    title: "欢迎来到我的站点"
    btn_text: "了解更多"
    btn_link: "/about"
  - type: "features"
    title: "核心功能"
    items:
      - name: "灵活排版"
        desc: "支持多种区块组合"
      - name: "内容分离"
        desc: "样式与内容互不干扰"
  - type: "markdown-content"
    content: |
      ### 这是一段自定义内容
      可以直接在这里写支持Markdown格式的文本,适合短内容区块。
---

然后在对应的layout文件(比如layouts/home/single.html)里循环渲染:

{{ range .Params.sections }}
  {{ $partialPath := print "sections/" .type ".html" }}
  {{ partial $partialPath . }}
{{ end }}

每个区块的结构写在单独的partial里,比如layouts/partials/sections/hero.html:

<section class="hero">
  <h1>{{ .title }}</h1>
  <a href="{{ .btn_link }}" class="btn">{{ .btn_text }}</a>
</section>

2. Markdown自定义分隔符 + 布局解析

如果区块内容以Markdown文本为主,可以在md文件里用特殊标记分隔不同区块,让layout自动识别并调用对应样式。

比如content/home/index.md内容:

---section:hero---
# 欢迎访问
这是英雄区块的描述文本,**支持Markdown格式**。

---section:features---
- 功能1:无需修改布局即可新增内容
- 功能2:每个区块的文本都能独立编辑

---section:testimonial---
> 来自用户的评价:这种方式既灵活又好维护!

然后在layout里解析这些分隔符:

{{ $rawSections := split .Content "---section:" }}
{{ range after 1 $rawSections }}
  {{ $split := split . "---" }}
  {{ $sectionType := index $split 0 | trim }}
  {{ $sectionContent := index $split 1 | markdownify }}
  
  {{ partial (print "sections/" $sectionType ".html") (dict "Content" $sectionContent "Page" $.Page) }}
{{ end }}

对应的partial比如layouts/partials/sections/testimonial.html:

<section class="testimonial">
  {{ .Content }}
</section>

3. Page Bundles管理独立区块内容

如果每个区块的内容特别复杂(比如包含独立的图片、大量文本),可以用Hugo的Page Bundle来拆分内容:

  1. 在content目录创建页面bundle:content/home/index.md
  2. 在同一目录下创建每个区块的md文件:hero.md、features.md、testimonial.md
  3. 在index.md的Front Matter里指定要加载的区块顺序:
---
title: "首页"
sections: ["hero", "features", "testimonial"]
---

然后在layout里循环加载这些子页面:

{{ range .Params.sections }}
  {{ $sectionPage := $.Site.GetPage "page" (print $.File.Dir .) }}
  {{ partial (print "sections/" . ".html") $sectionPage }}
{{ end }}

每个区块的内容直接写在对应的md文件里,比如content/home/features.md:

---
title: "核心功能"
---
### 功能一
详细的功能描述,支持任意Markdown格式。

### 功能二
配合partial的样式,能实现复杂的排版。

核心思路

本质是坚持内容与样式分离:所有可变内容都放在content目录的md文件或Front Matter里,layouts只负责渲染的结构和逻辑,这样既避免了layouts目录臃肿,也让内容编辑更直观。

内容的提问来源于stack exchange,提问作者Branko Tomic

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 11:22:16