Skip to content

Commit

Permalink
added URL hash support for post_link tag (#5356)
Browse files Browse the repository at this point in the history
  • Loading branch information
iliayatsenko authored Dec 2, 2023
1 parent 486de57 commit ea4f63c
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 2 deletions.
13 changes: 11 additions & 2 deletions lib/plugins/tag/post_link.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,19 @@ import type Hexo from '../../hexo';
*/
export = (ctx: Hexo) => {
return function postLinkTag(args: string[]) {
const slug = args.shift();
let slug = args.shift();
if (!slug) {
throw new Error(`Post not found: "${slug}" doesn't exist for {% post_link %}`);
}

let hash = '';
const parts = slug.split('#');

if (parts.length === 2) {
slug = parts[0];
hash = parts[1];
}

let escape = args[args.length - 1];
if (escape === 'true' || escape === 'false') {
args.pop();
Expand All @@ -33,7 +41,8 @@ export = (ctx: Hexo) => {
const attrTitle = escapeHTML(post.title || post.slug);
if (escape === 'true') title = escapeHTML(title);

const link = encodeURL(new URL(post.path, ctx.config.url).pathname);
const url = new URL(post.path, ctx.config.url).pathname + (hash ? `#${hash}` : '');
const link = encodeURL(url);

return `<a href="${link}" title="${attrTitle}">${title}</a>`;
};
Expand Down
4 changes: 4 additions & 0 deletions test/scripts/tags/post_link.js
Original file line number Diff line number Diff line change
Expand Up @@ -73,4 +73,8 @@ describe('post_link', () => {
it('should throw if post not found', () => {
should.throw(() => postLink(['bar']), Error, /Post not found: post_link bar\./);
});

it('should keep hash', () => {
postLink(['foo#bar']).should.eql('<a href="/foo/#bar" title="Hello world">Hello world</a>');
});
});

0 comments on commit ea4f63c

Please sign in to comment.