1. 程式人生 > 其它 >解決hexo無法使用iconfont阿里圖示

解決hexo無法使用iconfont阿里圖示


author: Nathan-niee
tags:
date: 2021-09-09-11:21


1. 前言

突發奇想想更換(新增)一些圖示用於一個簡單的導航,可是使用網路上的給出的教程Hexo-使用阿里iconfont圖示,無論無何都應用不了,圖示總是不顯示,於是就想著研究一下原理,魔改一下。

框架: hexo

主題: butterfly

2. 分析

hexo的圖示的生成其實是經過pug引擎渲染butterfly.yml檔案得來的。

預設的格式:

social:
	fa fa-xxx: url || title

例項:

social:
	fa fa-xxx: https://github.com/xxx || Github  

pug渲染程式碼:

each url, icon in theme.social
  a.social-icon(href=url_for(trim(url.split('||')[0])) target="_blank" 
  title=url.split('||')[1] === undefined ? '' : trim(url.split('||')[1]))
    i(class=icon)

上述例項會被pug渲染成如下:

<a class="social-icon" href="https://github.com/xxx" target="_blank" title="Github">
    <i class="fa fa-xxx"></i>
</a>

說明:

pug程式碼第一個行的url,icon分別的指代:

  1. 「:」後面的 https://github.com/xxx || Github

    url || title 這三個構成一個數組(包含三個元素)分別是https://github.com/xxx,||,Github

  2. 「:」前面的fa fa-xxx

    這個字串就是pug中的第一行的icon也就是第四行的icon

頁面渲染的過程:

yml檔案中編寫引數 ➡ pug接收引數 ➡ 渲染為html程式碼。

這裡引數就是 icon, url

經過上述得知所謂fas fa-xxx只是一個引數,是fontawesome圖示的class。如果想使用阿里iconfont只需要改為對一個class就行。其他引數可以不變。

3. 步驟

3.1. 獲取iconfont圖示

S1: 進入iconfont官網( 需註冊/登入 )。

S2: 搜尋選擇想要的圖示描述。

a

S3: 選擇想要的樣式,點選加入購物車。

a

S4: 點選頁面右上角的購物車圖示。

a

S5: 點選【新增至專案】➡ 新建專案 ➡ 輸入專案名 ➡ 點選確定。

S6: 點選生成程式碼。

S7: 點選【預覽字型】。


3.2. Hexo中使用

S1: 進入hexo-butterfly的butterfly.yml中,主要新增<script>標籤即可。

新增到 inject下的head下:

S2: 在themes\butterfly\source\css\custom.css新增樣式程式碼。

/* icon 通用樣式 */
.icon {
  width: 1em;
  height: 1em;
  vertical-align: -0.15em;
  fill: currentColor;
  overflow: hidden;
}

s3: 新增所需圖示的icon即可。

<svg class="icon" aria-hidden="true">
  <use xlink:href="#icon-xxx"></use>
</svg>

但這裡由於是模板所以需要先修改pug模板

進入themes\butterfly\layout\includes\header\social.pug新增如下程式碼。

(可以直接替換原有程式碼)

each url, icon in theme.social
  a.social-icon(href=url_for(trim(url.split('||')[0])) target="_blank" 
  title=url.split('||')[1] === undefined ? '' : trim(url.split('||')[1]))
    svg(class="icon" aria-hidden="true")
      use(xlink:href='#' + icon)

⚠️警告⚠️

pug嚴格注意格式(縮排)

S3: 新增圖示和連結。

上述工作是一次性的,後期就不需要的,後面如果想更換/新增圖示,只需要進行如下設定:

格式:

social:
	[圖示名]: [社交url] || [社交網站名稱]

例項:

social:
	icon-cnblogs: https://www.cnblogs.com/ || 部落格園

這裡的「圖示名」也就是阿里圖示的Symbol方式下的程式碼。

⚠️注意⚠️

如以後需要新增更多的圖示,可以選擇到購物車後加入專案,生成新的程式碼,替換原來的butterfl.ymlinjecthead<script>標籤即可。

3.3. 重新啟動hexo服務

效果:

渲染後的html程式碼:

相關文章: https://www.pugjs.cn/api/getting-started.html

學習就是不斷的熟悉,瞭解 從陌生到熟悉,再到了如指掌