Insert image caption in Hexo

Hexo provides some useful hook functions to manipulate the posts before or after rendering the posts. For the image caption, the operation can be processed in the after_post_render callback in which the caption is added after each image tag when the post is rendered. Just a few lines of code:

1
2
3
4
5
6
7
8
9
10
hexo.extend.filter.register('after_post_render', function(data) {
if (hexo.config.image_caption && hexo.config.image_caption.enable == true) {
// caption class name
let className = hexo.config.image_caption.class_name || 'image-caption';
if (data.layout == 'post' || data.layout == 'page' || data.layout == 'about') {
data.content = data.content.replace(/(<img [^>]*alt="([^"]+)"[^>]*>)/g, '$1' + '<span class="' + className + '">$2</span>');
}
}
return data;
});