Emacs/Jekelly html pre-rendering

平时在使用 org-mode 中,页面需要图片时可使用 org-attach 添加图片,依托于 org-mode 的带结构的文字这个特点,将图片放在指定的目录下 org-attach-directory 进行管理。同时 Jekyll 可以将 org-mode 文档中导出的内容经过渲染后发布成 html 页面。如果图片不多可以手动将 html 页面中的图片链接修改一下就可以让 html 中嵌入并显示图片了,一旦页面的图片过多或者经常修改页面同时部署时,就会感觉枯燥麻烦。所以就有了本文的需求:在 Jekyll 发布后自动部署图片和修改渲染后的 html 以正确显示页面图片。

1. 修改前的页面

_20230612_084305screenshot.png

2. 根据需要修改页面

以下是 ELisp 代码的改动,使用了 org-public-after-publishing-hook 添加一个自定义函数 +wd/handle-image-in-html ,目的是将图片复制到 Jekyll 的发布附件的目录并重命名(下划线名称不被 Jekyll 附件管理),随后将上一步中生成的 html 中图片链接修改为 Jekyll 发布附件后的路径。

(defun +wd/handle-image-in-html (origin-name html-name)
  (with-temp-buffer
    (insert-file-contents html-name)
    (goto-char (point-min))
    (let ((match-content ""))
      (while (re-search-forward "<img src=\"\\(file://.*?\\)\".*>" nil t)
        (setq match-content (match-string 1 nil))
        (let* ((image-name (file-name-nondirectory match-content))
               (image-src-path (substring match-content (length "file://")))
               (image-deploy-path (concat "/home/wd/Sync/blog/jekyll/images/"
                                          (substring (file-name-directory image-src-path)
                                                     (length "/home/wd/Sync/org/."))))
               (image-deploy-name (if (string-prefix-p "_" image-name)
                                      (substring image-name 1)
                                    image-name))
               (image-src-link (concat "/images/"
                                       (substring (file-name-directory image-src-path) (length "/home/wd/Sync/org/."))
                                       image-deploy-name)))
          (make-directory image-deploy-path t)
          ;; (shell-command (concat (executable-find "convert") " " image-src-path " -strip " (concat image-deploy-path image-deploy-name)))
          (copy-file image-src-path (concat image-deploy-path image-deploy-name) t)
          (replace-match image-src-link nil nil nil 1))))
    (write-region (point-min) (point-max) html-name)))

(setq org-publish-after-publishing-hook #'+wd/handle-image-in-html)

3. 修改后的页面

最终的结果就像现在页面这样,以后发布的时候可以专心图片的插入就可以了,不用去对图片链接进行特定的处理。

_20230612_084521screenshot.png