快轉到主要內容

Customization

查看原始碼編輯此頁 (外部連結)
首次發表:

Override Templates 此標題的連結

Hugo provides a robust mechanism for template overriding. If the default layout or functionality of a specific theme component does not meet your requirements, you can override it by recreating the file at the equivalent path within your project's root directory.

This approach ensures that your customizations remain intact while allowing the underlying theme to be updated independently.

Usage Example 此標題的連結

  • Customize Syntax Highlighting Style

    These commands generate CSS to chroma.css, overriding the theme's built-in chroma.css.

    # Mac/Linux
    (echo 'html[data-theme=light] {'; hugo gen chromastyles --style=emacs; echo '}') > assets/yore/components/code/chroma.css
    (echo 'html[data-theme=dark] {'; hugo gen chromastyles --style=evergarden; echo '}') >> assets/yore/components/code/chroma.css
    
    # Windows PowerShell
    # This command cannot run in CMD; it must run in PowerShell
    @("html[data-theme=light] {"; (hugo gen chromastyles --style=emacs); "}") | Add-Content -Path "assets/yore/components/code/chroma.css"
    @("html[data-theme=dark] {"; (hugo gen chromastyles --style=evergarden); "}") | Add-Content -Path "assets/yore/components/code/chroma.css"

    See all available styles in the Hugo's documentation (外部連結).

  • Customize Footer

    You can modify the theme's default footer without altering the original theme files, follow these steps:

    1. Locate the target partial in the theme directory: themes/hugo-yore/layouts/_partials/footer.html
    2. Create a corresponding file in your project root: layouts/_partials/footer.html
    3. Implement your custom HTML within this new file.

Extend Templates 此標題的連結

Yore provides reserved partial hooks within the _partials directory, allowing for content injection at specific locations. This method is preferred over full template overrides when appending or prepending code.

Available Extension Points 此標題的連結

Files in layouts/_partials:

FileDescription
extend-head.htmlInjected in the <head>, after main CSS and before all deferred JavaScript
extend-body-end.htmlInjected immediately before the closing </body> tag
comment.htmlInjected in the article pages
page/content-before.htmlInjected before {{ .Content }} in the page template
page/content-after.htmlInjected after {{ .Content }} in the page template
docs/content-before.htmlInjected before {{ .Content }} in the page template in docs
docs/content-after.htmlInjected after {{ .Content }} in the page template in docs

Files in assets:

FileDescription
css/imports.cssLoaded at the beginning of all CSS files and bundled into the full CSS
css/custom.cssLoaded at the end of all CSS files and bundled into the full CSS

Below are examples of how to use the extensions.

Example: Conditional Assets 此標題的連結

To load specific stylesheets for pages under the /events, edit layouts/_partials/extend-head.html:

layouts/_partials/extend-head.html
{{ if (eq .Type "events") }}
  {{ with resources.Get "css/events.css" }}
    {{ $eventsCSS := . | minify | fingerprint }}
    <link rel="stylesheet" href="{{ $eventsCSS.RelPermalink }}" integrity="{{ $eventsCSS.Data.Integrity }}">
  {{ end }}
{{ end }}

Example: Custom JS 此標題的連結

Yore uses swup.js for AJAX page transitions, so JS initialization and cleanup must be set up manually to work properly. Taking canvas-confetti as an example:

layouts/_partials/extend-head.html
<script type="importmap">
  {
    "integrity": {
      "https://cdn.jsdelivr.net/npm/canvas-confetti@1.9.3/+esm": "sha256-Xex6ozB/dORkRh5KdzsNEyA/x8jOt3/X1YiGBiw0ztU="
    }
  }
</script>
{{- $js := resources.Get "/js/custom-main.js" -}}
{{- $opts := dict "format" "esm" "minify" hugo.IsProduction "externals" (slice "yore-main") -}}
{{- $js = $js | js.Build $opts -}}
<script type="module" src="{{ $js.RelPermalink }}" integrity="{{ $js.Data.Integrity }}"></script>
assets/js/custom-main.js
import * as animation from "./animation.js";
import { swup } from "yore-main";

// Clean up when leaving the page
swup.hooks.before('content:replace', () => {
  animation.destroy();
});

// Initialize when entering the page
swup.hooks.on('content:replace', () => {
  animation.init();
});

// Initialize on first page load, when swup is not involved
animation.init();
assets/js/animation.js
let timer = null;
let confetti = null;
let token = 0;

export async function init() {
  // Only run if the target exists
  const target = document.querySelector('[data-confetti]');
  if (!target) return;

  const id = ++token;
  const module = await import('https://cdn.jsdelivr.net/npm/canvas-confetti@1.9.3/+esm');
  if (id !== token) return;

  confetti = module.default;
  timer = setInterval(() => {
    confetti({
      particleCount: 40,
      spread: 70,
      origin: { x: Math.random(), y: 0 },
    });
  }, 600);
}

export function destroy() {
  token++;
  clearInterval(timer);
  timer = null;
  confetti?.reset();
  confetti = null;
}

This adds checks, cleanup, and race condition handling, in exchange for smooth AJAX page transitions.

Customize CSS 此標題的連結

重要

CSS customization is intended for advanced users.

Yore provides an assets/yore/overrides/custom.css entry to include your own stylesheets. This file is loaded at the end of all CSS files and bundled into the full CSS.

Understanding Yore's 3-layered CSS architecture facilitates more effective customization.

Concept 此標題的連結

Tailwind (外部連結) and the typography plugin (外部連結) are responsible for the major layout framework, and the color/padding/margin of components are also set by Tailwind utilities. All other CSS settings are loaded by Hugo pipes as plain CSS instead of being compiled into the Tailwind bundle.

This shows how Yore's CSS files are loaded:

---
config:
  layout: elk
---
graph TB
    BASE["schemes/FILE_NAME.css<br>Layer 1: Define raw color values"]
    SEM["tokens.css<br>Layer 2: Semantic naming"]
    COMP["xxx.css<br>other CSS components"]
    CUSTOM["custom.css<br>"]

    IMPORT["import to main.css"]

    TW_TOKEN["tailwind/theme.css<br>Layer 3: Tailwind classes<br>Define Tailwind suffixes"]
    TW_PROSE["tailwind/typography.css<br>Configure prose styles"]
    TW_MAIN["tailwind/main.css<br>Main Tailwind entry file"]
    TW_COMPILED["tailwind/compiled.css<br>Compiled plain CSS"]

    FINAL["📦 main-bundle.css"]

    BASE ==> | #64;import | IMPORT
    SEM ==> | #64;import | IMPORT
    TW_COMPILED ==> | #64;import | IMPORT  
    COMP ==> | #64;import | IMPORT
    CUSTOM ==> | #64;import | IMPORT
    IMPORT --> | Hugo css.Build | FINAL

    TW_MAIN --> |compile to plain CSS outside Hugo| TW_COMPILED
    TW_TOKEN --> TW_MAIN
    TW_PROSE --> TW_MAIN

Tailwind is compiled into compiled.css when the theme is released, so users receive plain CSS. You do not need to install or run any Tailwind tooling to use the theme. All files outside the tailwind folder are loaded as plain CSS.

Variable Architecture 此標題的連結

Yore uses a simple three-layer variable system to make theming predictable and easy to customize:

  1. Base Colors: Raw color values defined in schemes/.
  2. Semantic Tokens: Purpose-based names defined in tokens.css.
  3. Tailwind Tokens: Tailwind utilities mapped to semantic tokens in theme.css.

Because Tailwind utilities reference CSS variables, you can customize the entire theme by overriding variables, no rebuild required.

Base Colors 此標題的連結

Schemes use an 11-step scale across three main color types:

:root {
  /* Neutral colors for backgrounds and text */
  --color-neutral-50: oklch(98.5% 0.003 60);
  /* ... steps 100 to 900 ... */
  --color-neutral-950: oklch(12% 0.004 35);

  /* Brand colors for main identity */
  --color-accent-50: oklch(97.5% 0.015 165);
  /* ... steps 100 to 900 ... */
  --color-accent-950: oklch(20% 0.03 165);

  /* Accent colors for highlights */
  --color-brand-50: oklch(98% 0.03 125);
  /* ... steps 100 to 900 ... */
  --color-brand-950: oklch(25% 0.06 125);
}

This is complete the same as Tailwind default levels. You can create your own schemes easily by using any Tailwind color generator (外部連結).

Yore natively supports the OKLCH color model, which allows you to define colors semantically. OKLCH separates colors into three components:

  • Lightness (L): How bright the color is
  • Chroma (C): How strong or vivid the color is
  • Hue (H): The color’s angle on the color wheel

OKLCH is much more predictable than RGB, where it is not possible to tweak a color by editing the RGB value. With OKLCH, you can adjust brightness, intensity, or hue independently, making it intuitive to adjust a certain just by value.

Learn more on the MDN documentation (外部連結).

Semantic Tokens 此標題的連結

assets/yore/core/styles/tokens.css defines all color nicknames. This avoids repeating color codes and ensures consistent appearance.

Example customization in assets/yore/core/css/schemes/custom.css:

html[data-theme='light'] {
  --muted: red;
  --muted-foreground: brown;
}


html[data-theme='dark'] {
  --muted: green;
  --muted-foreground: lime;
}

Tailwind Tokens 此標題的連結

Yore uses custom Tailwind tokens defined in assets/yore/core/tailwind/theme.css.

Semantic tokens are integrated into Yore's custom Tailwind tokens. Instead of default classes like bg-red-50, Yore uses bg-CUSTOM_TOKEN to maintain thematic consistency across the site.

The class structure uses standard Tailwind prefixes (text-, bg-, border-) paired with the custom suffixes. This results in classes such as text-muted or bg-brand. Since theme.css references variables from tokens.css, you can modify specific colors via CSS variables without rebuilding Tailwind.

Building Your Own TailwindCSS 此標題的連結

資訊

This is more advanced than custom.css customization and requires pnpm and TailwindCSS.

You can also build your own Tailwind CSS if you need extra Tailwind classes.

Steps:

  1. Install pnpm.
  2. Copy package.json and assets/yore/core/tailwind/ from the theme source.
  3. Run pnpm i.
  4. Use Tailwind classes like bg-red-500/87 and build with pnpm run build:css.
  5. Confirm compiled.css includes bg-red-500\/87.

Tailwind v4 scans all project files (外部連結), so Yore installed via Git submodule requires no additional setup. For Hugo module installation, vendor Yore first using hugo mod vendor (外部連結).

Yore also supports Hugo's built-in css.TailwindCSS (外部連結) function. This method isn't recommended for the following reasons:

  • Inconsistency: The same CSS works perfectly with Tailwind CLI but requires extra configuration with Hugo Pipe.
  • Lack of transparency: Hugo wraps Tailwind as a black box, so you have less control over the build process.
  • Harder debugging: The black box makes troubleshooting unintuitive.
  • Maintenance: Method 1 only needs a manual diff sync during theme updates. Method 2 requires debugging inside the Hugo environment.
警告

Hugo doesn't support pnpm with TailwindCSS. See #14852 (外部連結).

To use Hugo Pipe:

  1. Install the required packages.

    npm install @tailwindcss/cli @tailwindcss/typography @tailwindcss/forms tailwindcss
  2. Add the following to hugo.yaml.

    build:
      buildStats:
        enable: true
      cachebusters:
      - source: 'assets/notwatching/hugo_stats\.json'
        target: css
      - source: '(postcss|tailwind)\.config\.js'
        target: css
    
    module:
      imports:
        - path: github.com/ZhenShuo2021/hugo-yore
      mounts:
      - source: assets
        target: assets
      - disableWatch: true
        source: hugo_stats.json
        target: assets/notwatching/hugo_stats.json
    
    security:
      exec:
        allow:
        - ^(dart-)?sass$
        - ^go$
        - ^git$
        - ^node$
        - ^postcss$
        - ^tailwindcss$
  3. Set params.hugoTailwind: true in hugo.yaml.

文章關聯

無障礙設定