iT邦幫忙

2021 iThome 鐵人賽

1
Modern Web

MacOS新手操作指令學習紀錄,成為裝B前端工程師之路系列 第 33

[Day33] Hexo x NexT - 顯示最新文章、導入Google Analytics 的坑

先前使用 Hueman 的主題,但是有些 plugin 還需要花時間研究才能加進去,後來決定用許多人推薦的 NexT,因為已經整合許多 plugin,只要修改設定檔就可以使用,但想像很美好,實際做起來也是不少問題...


Themes 架構變更

過去 NexT 主題和其他多數主題一樣會安裝在 themes 的資料夾底下,現在則是放到 node_modules 裡面,如果需要修改樣式設定,直接在網站的根目錄建立 _config.主題名稱.yml 檔案,再去調整設定值。

設定檔內容可以到 node_modules/hexo-theme-next 資料夾底下找他的 config.yml ,複製回網站根目錄來改(記得要改檔名,不然會跟原本 hexo 的 config 衝突),這種作法主要是讓主題的原始碼不要被更動,後續更新主題版本的時候比較不會出問題吧!

本篇文章使用版本
Hexo: 5.4.0
NexT: 8.8.2


左側選單顯示最新文章

NexT 已經有 hexo-related-popular-posts 套件來顯示最新文章列表的功能,但是這個套件似乎沒辦法正常運作,網路上有不少教學文章,但是 NexT 的架構檔案格式從 swig 改成 njk,照著舊的文章貼上不會成功,設定步驟如下:

  1. 修改 _config.next.js,設定自定樣式檔案和近期文章的設定

    // 套用自定樣式檔案
    custom_file_path:
      sidebar: source/_data/sidebar.njk
    
    ...
    
    // 加入近期文章設定
    recent_posts_title: 近期文章
    recent_posts_layout: block
    recent_posts: true
    
  2. 在網站根目錄的 source 資料夾新增 _data 資料夾,再建立 sidebar.njk 檔案。

  3. sidebar.njk 檔案裡面加入下段程式碼(跟 swig 版本就只差了一個 .toArray() )

    {%- if theme.recent_posts %}
      <div class="links-of-blogroll motion-element {{ "links-of-blogroll-" + theme.recent_posts_layout  }}">
      <div class="links-of-blogroll-title">
          <!-- 設定你要的fa fa icon-->
          <i class="fa fa-history fa-{{ theme.recent_posts_icon | lower }}" aria-hidden="true" style="margin: 1rem 0.25rem 0.5rem 0"></i>
          {{ theme.recent_posts_title }}
      </div>
      <ul class="links-of-blogroll-list">
          {%- set posts = site.posts.sort('-date') %}
          {%- for post in posts.slice('0', '5').toArray() %}
          <li>
              <a href="{{ url_for(post.path) }}" title="{{ post.title }}" target="_blank">{{ post.title }}</a>
          </li>
          {%- endfor %}
      </ul>
      </div>
      {%- endif %}
    
  4. 重新生成頁面,完成。

參考文章:大魔術熊貓工程師


導入Google Analytics

  1. NexT 已經有做好相關配置,只要在 _config.next.js 設定就好:

    google_analytics:
      tracking_id: 自己的id
    
  2. 有關這個追蹤 ID 在 NexT 的文件中有說明需要 UA 開頭,但是許多網路教學照著做只會拿到 G 開頭的追蹤碼,參考下個步驟的連結,乖乖申請 UA 開頭追蹤碼就沒問題了。

  3. Google Analytics 取得『UA-』追蹤ID 官方文件


最後也分享一下成果網站,歡迎大家不吝指教,謝謝!


上一篇
[Day32] Hexo - 修改主題樣式及一些問題排除
系列文
MacOS新手操作指令學習紀錄,成為裝B前端工程師之路33
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言