Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added URL hash support for post_link tag #5356

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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>');
});
});
Loading