GitHub ソースリンク

概要

gohan は各記事のMarkdownソースファイルへのGitHub URLをテンプレートに公開できる。テーマ側で「GitHubで編集を提案する」リンクを生成するための機能であり、設定ファイルのみで制御できる。テーマ作者はGoコードを書く必要はない。

設定

config.yamlsite ブロックに github_repo(と任意で github_branch)を追加する:

site:
  title: "My Blog"
  base_url: "https://example.com"
  github_repo: "https://github.com/owner/repo"   # 必須(空の場合は機能無効)
  github_branch: "main"                           # 省略時は "main"
フィールド デフォルト 説明
github_repo string "" (無効) GitHubリポジトリのベースURL
github_branch string "main" リンク先ブランチ

github_repo が空の場合、機能は無効となる。後述のテンプレート例で使っている {{with}} ガードが自動的に処理する。

データモデル

SiteConfig に2フィールドを追加:

// SiteConfig holds site-wide metadata.
type SiteConfig struct {
    // ...既存フィールド...

    // GitHubRepo はサイトのコンテンツをホストするGitHubリポジトリのベースURL
    // (例: "https://github.com/owner/repo")。設定すると、テンプレートで
    // .ContentPath を使って「このページを編集」リンクを生成できる。
    GitHubRepo   string `yaml:"github_repo"`
    // GitHubBranch は編集URLに使用するブランチ。デフォルトは "main"。
    GitHubBranch string `yaml:"github_branch"`
}

ProcessedArticle に1フィールドを追加:

// ProcessedArticle holds derived data generated by the renderer.
type ProcessedArticle struct {
    // ...既存フィールド...

    // ContentPath はコンテンツディレクトリからのMarkdownファイルの相対パス
    // (例: "posts/hello-world.md")。GitHubの編集・閲覧リンク生成に使用。
    ContentPath string
}

テンプレートでの使い方

最もシンプルな記事テンプレートのスニペット:

{{with .Config.Site.GitHubRepo}}
<a href="{{.}}/blob/{{$.Config.Site.GitHubBranch}}/content/{{$.Article.ContentPath}}"
   target="_blank" rel="noopener noreferrer">
  GitHubで編集を提案する
</a>
{{end}}

注意: URL内の content/ プレフィックスは、Markdownファイルがリポジトリルートの content/ ディレクトリに存在することを前提としている。レイアウトが異なる場合は このプレフィックスを適宜変更すること。

実装メモ

  • ContentPathinternal/processor/processor_impl.gocomputeContentPath で計算する。 filepath.Rel(contentDir, article.FilePath) を呼び出した後、filepath.ToSlash でフォワードスラッシュに正規化する。
  • GitHubBranch のデフォルト値("main")は internal/config/config.goapplyDefaults 関数で適用される。
  • 追加のビルドステップやプラグインは不要。

関連ページ