hugo Hugo blog & PaperMod

整理建這個blog遇到的各種踩雷實錄,持續更新中…

✏️本文最後更新於 2023-08-20:文章加入手寫字卡、資料夾更名(ac3b0ec)

安裝hugo

網路資源很多,先略XD

(記得添加hugo指令到環境變數,才可以在任意資料夾使用hugo相關指令喔)

常用hugo指令

- 建立新blog 
> hugo new site <blog_name> -f yml

- 下載PaperMod主題
> git clone https://github.com/adityatelange/hugo-PaperMod themes/PaperMod --depth=1

- 建立新文章
> hugo new posts/<new_post>.md
# 記得要改draft: false才會出現在文章列表中(或是在 config.yml中加入 buildDrafts: true )

- 本機端預覽部落格(預設會在localhost:1313)
> hugo server

使用主題

# 在 config.yml 中加入所選主題
> theme: "PaperMod"

PaperMod 主題

  • 新增文章時間軸(Archives)

    1. 建立 archive.mdcontent資料夾下 content/archive.md
    ---
    title: "文章列表"
    layout: "archives"
    url: "/archives/"
    summary: archives
    ---
    

    https://github.com/adityatelange/hugo-PaperMod/wiki/Features#archives-layout

  • 新增搜尋頁面(search page)

    1. 把以下設定加到config.yml
    # for search page
    outputs:
      home:
        - HTML
        - RSS
        - JSON
    
    1. 建立 search.mdcontent資料夾下 content/search.md
    ---
    title: "搜尋" # in any language you want
    layout: "search" # is necessary
    # description: "Description for Search"
    summary: "search"
    placeholder: "搜尋文章關鍵字"
    ---
    
    1. 如不希望該文章被搜索到,則添加以下於文章的frontmatter區塊
    ---
    searchHidden: true
    ---
    
  • 設定文章模板

    每次新增文章時會自動帶入的部分。參考

    找到 archetypes/default.md 並修改。

    ---
    title: "{{ replace .Name "-" " " | title }}"
    date: {{ .Date }}
    draft: false
    
    # "怎麼重新整理都沒用?這篇教你清除永無止盡的瀏覽器重新轉址(redirection)!"
    # 字數不要超過以上
    summary: "" # 首頁顯示的文字總結段落
    
    categories: 
    - 行山
    - 技術
    - 訓練
    tags: # 自由新增
    - 
    - 
    
    author: ["小M平"]
    
    isCJKLanguage: true # 是否是中文(chinese,japanese,korea) 字數判斷用
    comments: true
    showToc: true # 顯示目錄
    TocOpen: true # 預設打開目錄
    hidemeta: false # 是否隱藏meta訊息(ex:發布日期、作者...etc)
    disableShare: false # 取消社群分享區塊
    showbreadcrumbs: true # 於頂部顯示文章路徑
    ShowWordCounts: true
    ShowReadingTime: true
    ShowLastMod: true
    
    cover:
        image: "" # 封面圖片路径 (ex:clear-301-redirection-cache-chrome/cover.jpg)
        caption: "" # 封面圖片底部描述
        alt: ""
        relative: false
    ---
    
  • 社群連結(鑲嵌strava, ig post)

    基本上用rawhtml這個shortcode搭配iframe鑲嵌的方式比較簡單,未來移植性也比較高

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    
    // strava activities
    {{< rawhtml >}}
    <div class='strava-embed-placeholder' data-embed-type='activity' data-embed-id='7279049209'></div><script src='https://strava-embeds.com/embed.js'></script>
    {{< /rawhtml >}}
    
    // strava recent activities
    {{< rawhtml >}}
    <iframe height='454' width='300' frameborder='0' allowtransparency='true' scrolling='no' src='https://www.strava.com/athletes/34128612/latest-rides/f672808af3343beece46ac192ff9a69e41e3d6cd'></iframe>
    {{< /rawhtml >}}
    
    // ig post
    {{< rawhtml >}}
    <iframe height='454' width='300' frameborder='0' allowtransparency='true' scrolling='no' src='https://www.instagram.com/p/Ccf9RZKBoN0/embed/'></iframe>
    {{< /rawhtml >}}
    

Hugo/PaperMod Shortcode

Shortcode 可以看作是「一小塊 HTML 程式片段」,與 Hugo Template 不同的是,前者通常運用在「插入特定用途」、「重複使用」的片段語法到 markdown 內容中,而後者則是作為 markdown content 的外殼載體、或是佈局規劃等,用以構成我們最後呈現的視圖頁面 (View)。 — 來源:iT邦

有興趣研究更詳細的shortcode設定,可以參考這篇 以及這篇

  • figure

    內建shortcode,可直接在文章中內嵌圖片並做寬度/標題設定

    {{< figure  src="..." title="..." width="100%" >}}
    
  • imgur

    單純為了放上傳到imgur的影片(如果是單純imgur本身我會用上面figure的方式,還可以指定更多參數)

    新增/layouts/shortcodes/imgur.html

    <div class="embed imgur-video" style="padding: 10px;">
        <video controls="" name="media" style="width: 50%;">
            <source src='https://i.imgur.com/{{ .Get "id" }}.mp4' type="video/mp4">
        </video>
    </div>
    

    新增完後,以後在文章中即可使用{{< imgur id="" >}}語法來嵌入 imgur mp4

    參考自這篇 還有這篇

  • youtubestartend

    可指定youtube影片開始跟結束的時間。ref

    ex: {{< youtubestartend siVSC7tZVek 72 82 >}}

    新增/layouts/shortcodes/youtubestartend.html

    <div style="position: relative; padding-bottom: 56.25%; padding-top: 30px; height: 0; overflow: hidden;">
        <iframe src="http://www.youtube-nocookie.com/embed/{{ index .Params 0 }}?start={{ index .Params 1 }}&end={{ index .Params 2}}"
        style="position: absolute; top: 0; left: 0; width: 100%; height: 100%;" allowfullscreen frameborder="0" title="YouTube Video"></iframe>
    </div>
    

css 修改

  • code 區塊設定max-height assets/css/common/post-single.css
    .post-content pre code {
        max-height: 30em;
    }
    
  • 取消 footnote hr分隔線 assets/css/common/post-single.css
    /* 取消footnote的hr分隔線 */
    .footnotes hr {
        display: none;
    }
    /* 取消footnote的hr分隔線 */
    
  • 讓tags跟categories頁面的文章也呈現縮圖 assets/css/common/post-entry.css ref
    .tag-entry .entry-cover {
        display: flex;
    }
    

Hugo frontmatter區塊參數說明

設置評論區/comment systems

hugo 系統自訂性非常高,內建整合老牌的Disqus服務,不過似乎有個資的問題,再加上不是每個人都有github帳號,幾經思量後決定自己host一個comment system。

想看hugo與disqus的設定可看這篇 ,基本上照著做就行。

查照hugo支援的comment system列表請看這裡


將文章大綱(TOC, table of content)改到側邊

參考這篇

首頁縮圖調整

參考這篇

自定義post_meta顯示

  • 最後編輯(Lastmod)

    會根據frontmatter中的順序取值。官網說明

    • :git:會去抓git提交紀錄的日期,且必須於config.yml中啟用enableGitInfo = true(沒試成功)
    • :fileModTime:根據本機的文件最後修改紀錄
    • lastmod:可以在文章的frontmatter區塊中直接設定
    • date:可以在文章的frontmatter區塊中直接設定
    • publishDate:文章發布的日期

    config.yml

    frontmatter:
        lastmod:
        - :git
        - :fileModTime
        - lastmod
        - date
        - publishDate
    
  • 在post_meta塞svg

    iconset: https://package.elm-lang.org/packages/1602/elm-feather/1.0.0/FeatherIcons 參考別人的post_meta.html: https://github.com/reorx/hugo-PaperModX/blob/master/layouts/partials/post_meta.html

  • 我的post_meta

    layouts/partials/post_meta.html

    {{ $date := .Date.Format "02.01.2006" }}
    {{ $lastmod := .Lastmod.Format "02.01.2006" }}
    
    {{- $scratch := newScratch }}
    
    
    {{- if not .Date.IsZero -}}
    {{- $scratch.Add "meta" (slice (printf "<span title='%s'>張貼: %s</span>" (.Date) (.Date | time.Format (default "2006-01-02" site.Params.DateFormat)))) }}
    {{- end }}
    
    {{- if ne $lastmod $date -}}
    {{- $scratch.Add "meta" (slice (printf "<span title='%s'>最後編輯: %s</span>" (.Lastmod) (.Lastmod | time.Format (default "2006-01-02" site.Params.DateFormat)))) }}
    {{- end }}
    
    {{- if (.Param "ShowReadingTime") -}}
    {{- $scratch.Add "meta" (slice (i18n "read_time" .ReadingTime | default (printf "%d min" .ReadingTime))) }}
    {{- end }}
    
    {{- if (.Param "ShowWordCount") -}}
    {{- $scratch.Add "meta" (slice (i18n "words" .WordCount | default (printf "%d words" .WordCount))) }}
    {{- end }}
    
    {{- with (partial "author.html" .) }}
    {{- $scratch.Add "meta" (slice .) }}
    {{- end }}
    
    {{- with ($scratch.Get "meta") }}
    {{- delimit . "&nbsp;|&nbsp;" -}}
    {{- end -}}
    

    參考

    1. 這篇
    2. https://github.com/adityatelange/hugo-PaperMod/discussions/775
    3. https://gohugo.io/getting-started/configuration/#:~:text=date%20handlers%20are%3A-,%3AfileModTime,-Fetches%20the%20date
    4. 別人的範本
    5. 官網
    6. https://mertbakir.gitlab.io/hugo/last-modified-date-in-hugo/
    7. https://www.jacksonlucky.net/posts/use-lastmod-with-papermod/
  • 我的 config.yml

    # baseURL: "https://thriving-tartufo-c36de5.netlify.app/"
    baseURL: "https://www.lilmp.com"
    languageCode: en-us
    title: LilMP | 小M平
    theme: "PaperMod"
    
    paginate: 5 # 首頁文章筆數
    
    defaultContentLanguage: "zh-tw"
    
    enableGitInfo: true
    
    frontmatter:
    date:
    - date
    - publishDate
    - lastmod
    expiryDate:
    - expiryDate
    lastmod:
    - :git
    - :fileModTime
    - lastmod
    - date
    - publishDate
    publishDate:
    - publishDate
    - date
    
    enableRobotsTXT: true
    buildDrafts: true
    buildFuture: false
    buildExpired: false
    
    googleAnalytics: UA-123-45
    
    minify:
    disableXML: true
    minifyOutput: true
    
    # FOR SEARCH PAGE
    outputs:
    home:
        - HTML
        - RSS
        - JSON
    
    params:
    env: production # to enable google analytics, opengraph, twitter-cards and schema.
    title: ExampleSite
    description: "ExampleSite description"
    keywords: [Blog, Portfolio, PaperMod]
    author: 小M平
    # author: ["Me", "You"] # multiple authors
    images: ["<link or path of image for opengraph, twitter-cards>"]
    DateFormat: "2006-01-02" # "January 2, 2006"
    defaultTheme: auto # dark, light
    disableThemeToggle: false
    
    ShowAllPagesInArchive: true
    mainSections:
        - posts
    
    ShowLastMod: true
    ShowReadingTime: true
    ShowShareButtons: true
    ShowPostNavLinks: true
    ShowBreadCrumbs: true
    ShowCodeCopyButtons: true
    ShowWordCount: true
    VisitCount: true
    ShowRssButtonInSectionTermList: true
    UseHugoToc: true
    disableSpecial1stPost: false
    disableScrollToTop: false
    comments: true
    hidemeta: false
    hideSummary: false
    showtoc: true
    tocopen: true
    
    
    
    # ShareButtons: ["facebook", "telegram"]
    
    
    # Display thumbnail image of each post on index pages (false: disabled, true: enabled)
    # 文章缩略图功能
    thumbnailImage: true
    # 缩略图位置,我觉得放在上面好看,如果用的小图片作缩略图
    # 可以放在(left或者right),设置此项会取代配置文件中默认在下边的设置
    thumbnailImagePosition: top
    # 这个下边默认就好了,暂时不清楚有什么影响
    autoThumbnailImage: yes
    metaAlignment: left
    
    assets:
        # disableHLJS: true # to disable highlight.js
        # disableFingerprinting: true
        # favicon: "<link / abs url>"
        # favicon16x16: "<link / abs url>"
        # favicon32x32: "<link / abs url>"
        # apple_touch_icon: "<link / abs url>"
        # safari_pinned_tab: "<link / abs url>"
    
    label:
        # text: "Home"
        # icon: /apple-touch-icon.png
        # iconHeight: 35
    
    # profile-mode
    profileMode:
        enabled: false
        title: "<Title>" # optional default will be site title
        subtitle: "This is subtitle"
        # imageUrl: "<image link>" # optional
        # imageTitle: "<title of image as alt>" # optional
        # imageWidth: 120 # custom size
        # imageHeight: 120 # custom size
        buttons:
        - name: Archive
            url: "/archive"
        - name: About
            url: "/about"
    
    
    
    # home-info mode
    homeInfoParams:
        Title: "Hi there. 我是小M平 \U0001F44B"
        Content: >
        - ### 心、技、體
    
        - 離開世界之前,一切都是過程。
    
        - Welcome to my blog. Below is where you can reach out to me.    
    
    socialIcons:
        - name: instagram
        url: "https://www.instagram.com/yenzichun"
        - name: strava
        url: "https://www.strava.com/athletes/34128612"
        - name: youtube
        url: "https://www.youtube.com/channel/UCuAlYrRVD7b63WGgcCcR1ww"
        - name: email
        url: "mailto:yenping074@gmail.com"
        - name: buymeacoffee
    
    analytics:
        google:
        SiteVerificationTag: "XYZabc"
        bing:
        SiteVerificationTag: "XYZabc"
        yandex:
        SiteVerificationTag: "XYZabc"
    
    cover:
        linkFullImages: false
        hidden: false # hide everywhere but not in structured data
        hiddenInList: false # hide on list pages and home
        hiddenInSingle: false # hide on single page
    
    # editPost:
    #   URL: "https://github.com/LilMP/LilMP-hugo-site/tree/master/content"
    #   Text: "Suggest Changes" # edit text
    #   appendFilePath: true # to append file path to Edit link
    
    # for search
    # https://fusejs.io/api/options.html
    fuseOpts:
        isCaseSensitive: false
        shouldSort: true
        location: 0
        distance: 1000
        threshold: 0.4
        minMatchCharLength: 0
        keys: ["title", "permalink", "summary", "content"]
    menu:
    main:
        - identifier: categories
        name: 分類
        url: /categories/
        weight: 10
        - identifier: tags
        name: 標籤
        url: /tags/
        weight: 20
        - identifier: archives
        name: 時間軸
        url: /archives/
        weight: 30
        - identifier: projects
        name: 專案
        url: /projects/
        weight: 40
        - identifier: about
        name: 關於
        url: /about/
        weight: 50
        - identifier: search
        name: 搜尋
        url: /search/
        weight: 60
        # - identifier: example
        #   name: example.org
        #   url: https://example.org
        #   weight: 30
    # Read: https://github.com/adityatelange/hugo-PaperMod/wiki/FAQs#using-hugos-syntax-highlighter-chroma
    # pygmentsUseClasses: true
    # markup:
    #     highlight:
    #         # anchorLineNos: true
    #         codeFences: true
    #         guessSyntax: true
    #         lineNos: true
    #         style: monokai
    

首頁配置

部屬上線

研究了很久,覺得最無腦的方式就是串接netlify(影片37:11分開始)

其他問題

  • 上傳到github後發現theme的css沒有載入

    打開F12檢查錯誤訊息 看是否為Failed to find a valid digest in the 'integrity' attribute for resource

    如果是的話於config.yml裡加上這行即可。來源

    params:
    assets:
        disableFingerprinting: true
    
  • blockquote 用法

{{< blockquote  author="..." source="..." link="..." title="..." >}}
some text here
{{< /blockquote >}}
  • Normal quote:

    This is a simple quote.

    Flying is learning how to throw yourself at the ground and miss.

    Douglas Adams, 《The Hichhikers Guide to the Galaxy》

  • Quote with author

    This is a quote with only an Author named Author2.

    Author2

  • Quote with author and source

    This is a quote from Author3 and source “source.”

    Author3 《Source》

  • Quote with author and link

    This is a quote from Author4 and links to https://www.google.com .

  • Quote with author, link and title

    This is a quote from Author5 and links to https://www.google.com with title “Google.”

  • Quote with author and a link longer than 32 characters, string is first cut at 32 characters then everything after the last forward slash is removed

    This is a quote from Author5 and links to https://twitter.com/CryptoGangsta/status/716427930126196737 which is longer than 32 characters. And this is a new line in the quote with the HTML br tag.

  • Test from the Octopress blockquote page at: http://octopress.org/docs/plugins/blockquote/

    Over the past 24 hours I’ve been reflecting on my life & I’ve realized only one thing. I need a medieval battle axe.

  • 設定文章中的互連 (2023.02.16 update)

    因為之前改動過permalink設定, 將網址統一為/year-month-day/slug/ 的形式。
    所以之前文章中有引用的部分超連結也需要改變

    原本做法: 假設要被連結的文章檔名為 hugo-papermod-blog.md
    原本是類似文件層級,../後面直接輸入"檔名"即可(hugo-papermod-blog.md)

    [架站║ Hugo部落格與PaperMod主題](../hugo-papermod-blog)
    

    不過因為現在網址多了/year-month-day/所以這樣會連不到。

    解決辦法:
    於該文章的front matter中設定aliases

    aliases:
        - /hugo-blog-settings/
    

    修改後: [超連結文字](/hugo-blog-settings) 就會自動連到對應的文章,也不用輸入/year-month-day/的網址前綴

不錯的hugo內容網站

  1. https://theryanlin.github.io/posts/2020/11/16/
  2. https://aiwlulu.github.io/
  3. https://www.odszz.com/
  4. https://www.sulvblog.cn/
  5. https://freepencil.com/2021/10/hugo-papermod%E8%B8%A9%E5%9D%91%E5%8E%86%E7%A8%8B/
  6. https://wenrongdev.com/posts/reflection-blog-1/

參考資料

  1. PaperMod features
  2. hugo-PaperMod Github
  3. hugo shortcodes-官網
  4. papermod FAQs
  5. hugo新手道場
  6. papermod github.io
  7. liva hugo
  8. PaperModX:這裡 、還有這裡

👇本文關鍵字

👇更多同分類文章


這篇文章到這裡結束囉!

如果覺得有點意思,不妨留個言跟我交流吧❤️
See you in the next post.

google adsense廣告區塊說明
真的很希望能給大家乾淨的閱讀空間,無奈小弟我也是有點經濟壓力,放在這裡是我能想到最不影響閱讀體驗的地方了
如果您願意「免費」給小弟一點支持,讓我可以繼續追尋運動員之路,希望可以動動手指點擊上面的廣告,感激不盡!
(點擊一次我約可以得到0.01美元,但必須累積到100美元才可以真的領出來@@)



留言 0
您的留言是我持續寫文的動力~~