Набор tag plugins для Hexo

31 июля 2022. Комментарии .

Я уже много лет пользуюсь генератором статических сайтов Hexo. За это время написал для собственного удобства несколько tag plugins (аналог shortcodes в генераторе hugo). Написаны они коряво и подходят для очень ограниченных или специфических условий, поэтому публиковать как готовый продукт я не стал.

Также эти плагины доступны в теме helix.

Оглавление #

Использование #

Разместите файлы prompt.js, jg.js, gif.js, comment.js с приведенным ниже содержанием в <root>/themes/<theme>/scripts/ или в <root>/scripts/.

prompt tag #

prompt.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
'use strict';

/**
* Prompt tag by lisakov.com
*
* Syntax
*
* {% prompt [NAME] [DIR] [SYMBOL] [PREFIX] %}
* code
* code
* {% endprompt %}
*
* Examples
*
* {% prompt root 0 # %} → root #
* {% prompt root /dir # %} → root /dir #
* {% prompt livecd ~ # %} → livecd ~ #
* {% prompt user /dir $ %} → user /dir $
* {% prompt user 0 $ %} → user $
* {% prompt user %} → user $
* {% prompt livecd ~ # (chroot) %} → (chroot) livecd ~ #
*
*/

hexo.extend.tag.register('prompt', function(args, content){
args.unshift('prompt'); // make first argument args[1] not args[0]
var name='user';
var dir='';
var symbol='$';
var prefix='';
var promptclass = 'promptuser';
if (args.length > 1) {
name = args[1];
dir = args[2]+' ';
symbol = args[3];
}
if (typeof args[1] !=='undefined' && args[1].indexOf('root') >-1 || args[1]=='livecd') {
promptclass = 'promptroot';
}
if (args[2]=='0' || typeof args[2] == 'undefined') { dir = ''; }
if (args[3]=='0' || typeof args[3] == 'undefined') { symbol = ''; }
if (typeof args[4] !== 'undefined') { prefix = args[4] + ' '; }

var lines = content.split(/\r\n|\r|\n/).length+1
var gutter='';
var i=1;
for (i=1; i<lines; i++) {
gutter += prefix+"<span class='"+promptclass+"'>"+name+"</span> <span class='promptdir'>" + dir + symbol + "</span><br>"
}

var table = '<figure class="highlight prompt"><table><tr><td class="gutter"><pre>' + gutter + '</pre></td><td class="code"><pre>' + content + '</pre></td></tr></table></figure>';

return table;

}, {ends: true});

Пример #

1
2
3
4
{% prompt root ~ # %}
mkdir -p /mnt/usb
mount -t vfat /dev/sdb1 /mnt/usb
{% endprompt %}

Выдаст следующий код (в одну строку, но для удобства здесь я сделал читаемый вариант):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<figure class="highlight">
<table>
<tr>
<td class="gutter">
<pre>
<span class='promptroot'>root</span> <span class='promptdir'>~ #</span><br>
<span class='promptroot'>root</span> <span class='promptdir'>~ #</span><br>
</pre>
</td>
<td class="code">
<pre>mkdir -p /mnt/usb
mount -t vfat /dev/sdb1 /mnt/usb
</pre>
</td>
</tr>
</table>
</figure>

При моих стилевых файлах это выглядит так:

root ~ #
root ~ #
mkdir -p /mnt/usb
mount -t vfat /dev/sdb1 /mnt/usb

И на всякий случай картинка (так это выглядело в 2022 году):

jg tag #

Тэг-плагин для создания плиток из картинок с помощью js-библиотеки justifiedgallery. Каждую картинку в плитке делает ссылкой, открывающей крупный вариант, другая js-библиотека magnificpopup.

Я размещаю картинки для конкретной записи по адресу lisakov.com/images/post/, а их маленькие версии по адресу lisakov.com/images/post/thumbs/. Есть возможность указать thumbs_dir явно или поставить thumbs_dir=none, если уменьшенных изображений нет.

С некоторых пор я стал пользоваться этим же тэгом для одиночных фотографий, подгружая только magnificPopup без justifiedgallery.

jg.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
'use strict';

/**
* jg tag by lisakov.com
*
* Examples jg
*
* {% jg img_path=https://lisakov.com/images/ thumbs_dir=800 thumbs_dir2=2000 lastonly=true %}
* imagename1.jpg
* imagename2.jpg "Title with description for imagename2"
* {% endjg %}
*
* Arguments
*
* path:
* path to images (img_path)
* default: 'https://lisakov.com/images/'
*
* thumbs_dir:
* path to thumbs (appended to img_path)
* default: 'thumbs/'
* none: no thumbs, use original images, useful for a single image
*
* thumbs_dir2:
* path to medium thumbs (appended to img_path)
* default: '800/'
* if lastonly=true, last element gets
*
* lastonly:
* <bool> (if true, use larger thumbs or original only for the last item)
* default: false
* use img_path + 'thumbs/' for every image except for the last,
* last will be img_path + thumbs (equals to anything, if thumbs=undefined, use original)
*
*/

hexo.extend.tag.register('jg', function(args, content){
// set defaults
var img_path = 'https://lisakov.com/images/';
var thumbs_dir = 'thumbs/';
var thumbs_dir2 = '800/';
var lastonly = 'false';
// read arguments and replace defaults if needed
args.forEach((el, idx) => {
if (el.includes('img_path=')) { img_path = el.replace('img_path=',''); }
if (el.includes('lastonly=')) { lastonly = el.replace('lastonly=',''); }
if (el.includes('thumbs_dir=')) {
thumbs_dir = el.replace('thumbs_dir=','');
thumbs_dir += thumbs_dir.endsWith("/") ? "" : "/" //add trailing slash if not present
if (thumbs_dir.includes('none')) { thumbs_dir=''; }
}
if (el.includes('thumbs_dir2=')) {
thumbs_dir2 = el.replace('thumbs_dir2=','');
thumbs_dir2 += thumbs_dir2.endsWith("/") ? "" : "/" //add trailing slash if not present
if (thumbs_dir2.includes('none')) { thumbs_dir2 = ''; }
}
});

// Перебираем все строки
var lines = content.split(/\r\n|\r|\n/);
lines.forEach((element, index, array) => {
// Если нет lastonly=true
if (lastonly === 'false') {
// Если в строке только imgname без title
if (lines[index].indexOf('"') === -1) {
lines[index] = '<a href=" ' + img_path + element + '"><img src="' + img_path + thumbs_dir + element + '"/></a>';
// Если в строке imgname + "title"
} else {
var title = lines[index].match(/"([^']+)"/)[1];
var img_name = lines[index].split(' ')[0];
lines[index] = '<a href=" ' + img_path + img_name + '"' + 'title="' + title + '"><img src="' + img_path + thumbs_dir + img_name + '"/></a>';
}
// Если lastonly=true
} else {

// Если элемент ПОСЛЕДНИЙ
if (index === array.length - 1) {
// Если в строке только imgname без title
if (lines[index].indexOf('"') === -1) {
lines[index] = '<a href=" ' + img_path + element + '"><img src="' + img_path + thumbs_dir2 + element + '"/></a>';
// Если в строке imgname + "title"
} else {
var title = lines[index].match(/"([^']+)"/)[1];
var img_name = lines[index].split(' ')[0];
lines[index] = '<a href=" ' + img_path + img_name + '"' + 'title="' + title + '"><img src="' + img_path + thumbs_dir2 + img_name + '"/></a>';
}

// Если элемент НЕ последний
} else {
// Если в строке только imgname без title
if (lines[index].indexOf('"') === -1) {
lines[index] = '<a href=" ' + img_path + element + '"><img src="' + img_path + thumbs_dir + element + '"/></a>';
// Если в строке imgname + "title"
} else {
var title = lines[index].match(/"([^']+)"/)[1];
var img_name = lines[index].split(' ')[0];
lines[index] = '<a href=" ' + img_path + img_name + '"' + 'title="' + title + '"><img src="' + img_path + thumbs_dir + img_name + '"/></a>';
}
}

}
});

return '<div class="jg">' + lines.join(' ') + '</div>';
}, {ends: true});

Для работы justifiedgallery и magnificPopup надо на странице подгрузить файлы библиотек (указав настоящие пути):

1
2
3
4
<link rel="stylesheet" href="justifiedGallery.min.css" />
<script src="jquery.justifiedGallery.min.js"></script>
<script src="magnific-popup.js" ></script>
<link rel="stylesheet" href="magnific-popup.min.css" />

Тэг-плагин добавляет класс .js к галерее, и надо сообщить библиотеке, с чем ей надо работать (указаны мои настройки):

1
2
3
4
5
6
7
<script>
$('.jg').justifiedGallery({
rowHeight : 130,
lastRow : '<%=page.justifiedgallery %>',
margins : 2
});
</script>

Библиотеке magnificPopup тоже говорим, что нужно работать с тем же классом jg:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<script>
$('.jg').magnificPopup({
delegate: 'a',
type: 'image',
verticalFit: true,
gallery: { enabled:true }
});
$(document).ready(function() {
$('.popup-with-zoom-anim').magnificPopup({
type: 'inline',
fixedContentPos: false,
fixedBgPos: true,
overflowY: 'auto',
closeBtnInside: true,
preloader: false,
gallery: {
enabled: true,
navigateByImgClick: true,
preload: [0,1] // Will preload 0 - before current, and 1 after the current image
},
midClick: true,
removalDelay: 300,
mainClass: 'my-mfp-zoom-in'
});
});
</script>

Разумеется, все, что внутри тегов <script>, удобно подгружать по указаниям justifiedgallery: <left/center/right/justify/nojustify> и magnificpopup: true во front-matter, настроив файлы themes/themename/layout/_partial/head.ejs и after_footer.ejs таким образом:

1
2
3
<% if (page.justifiedgallery) { %>
...
<% } %>

Пример #

1
2
3
4
5
{% jg img_path=https://lisakov.com/images/pu-2021/ %}
map-3.png "ESRI Satellite"
map-1.png "10-километровка"
map-2.png "Google Terrain"
{% endjg %}

дает следующий код (в одну строку, но тут я сделал читаемо для удобства просмотра):

1
2
3
4
5
6
7
8
9
10
11
<div class="jg">
<a href=" https://lisakov.com/images/pu-2021/map-3.png"title="ESRI Satellite">
<img src="https://lisakov.com/images/pu-2021/thumbs/map-3.png"/>
</a>
<a href=" https://lisakov.com/images/pu-2021/map-1.png"title="10-километровка">
<img src="https://lisakov.com/images/pu-2021/thumbs/map-1.png"/>
</a>
<a href=" https://lisakov.com/images/pu-2021/map-2.png"title="Google Terrain">
<img src="https://lisakov.com/images/pu-2021/thumbs/map-2.png"/>
</a>
</div>

Браузер отображает это так:

gif tag #

Включение/выключение анимации по щелчку с помощью библиотеки gifonclick.js. Не забудьте ее подгрузить на странице.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
'use strict';

/**
* gifonclick tag by lisakov.com
*
* Syntax:
* {% gif image.png animation.gif %}
*/


hexo.extend.tag.register('gif', function(args){
var img_path = args[0];
var gif_path = args[1];
return '<div class="cf" style="text-align:center"> <figure> <img src="' + img_path + '" data-alt="' + gif_path + '"></figure></div>'
});

Я использую следующие стили.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
.cf figure {
display: inline-block;
margin: 5 auto;
padding: 0px;
position: relative;
cursor: pointer;
}
.cf figure:before,
.cf figure:after {
position: absolute;
}
.cf figure:before {
content: url('https://lisakov.com/images/pbg.png');
display: inline-block;
left: 45%;
top: 45%;
}
.cf figure:after {
content: 'GIF';
position: absolute;
display: inline-block;
width: 40px;
text-align: center;
top: 47px;
right: 12px;
font-size: 11px;
font-weight: 600;
padding: 0px;
border-radius: 3px;
color: #fff;
background-color: rgba(170, 178, 189, 0.1);
}
.cf figure.play:before {
display: none;
}
.cf figure.play:after {
color: #fff;
background-color: #8CC152;
}
.cf figcaption {
text-align: center;
padding-top: 15px;
font-size: 14px;
color: #8d9bad;
}
.cf figcaption a {
color: #59687b;
text-decoration: none;
}

comment tag #

Иногда оставляю неоформленные мысли в markdown файлах. Удалить жалко, но хранить отдельно не хочется. Все, что будет внутри этого тэга, генератор проигнорирует.

1
2
3
4
5
6
7
8
9
10
11
12
13
'use strict';

/**
* Comment tag by lisakov.com
*
* {% comment %}
* Text here won't be rendered
* {% endcomment %}
*
*/

hexo.extend.tag.register('comment', function(args, content){
}, {ends: true});