Skip to content

Commit

Permalink
feat: add option to use slug as title of post (#5470)
Browse files Browse the repository at this point in the history
Signed-off-by: Uiolee <[email protected]>
Co-authored-by: Sukka <[email protected]>
  • Loading branch information
uiolee and SukkaW authored May 17, 2024
1 parent 6d880a2 commit 069ac38
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 2 deletions.
2 changes: 2 additions & 0 deletions lib/hexo/default_config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,8 @@ export = {
exclude_languages: [],
strip_indent: true
},
use_filename_as_post_title: false,

// Category & Tag
default_category: 'uncategorized',
category_map: {},
Expand Down
10 changes: 8 additions & 2 deletions lib/plugins/processor/post.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,8 +71,8 @@ function processPost(ctx: Hexo, file: _File) {
const { path } = file.params;
const doc = Post.findOne({source: file.path});
const { config } = ctx;
const { timezone: timezoneCfg } = config;
const updated_option = config.updated_option;
const { timezone: timezoneCfg, updated_option, use_slug_as_post_title } = config;

let categories, tags;

if (file.type === 'skip' && doc) {
Expand Down Expand Up @@ -110,6 +110,12 @@ function processPost(ctx: Hexo, file: _File) {
if (!preservedKeys[key]) data[key] = info[key];
}

// use `slug` as `title` of post when `title` is not specified.
// https://github.com/hexojs/hexo/issues/5372
if (use_slug_as_post_title && !('title' in data)) {
data.title = info.title;
}

if (data.date) {
data.date = toDate(data.date);
} else if (info && info.year && (info.month || info.i_month) && (info.day || info.i_day)) {
Expand Down
26 changes: 26 additions & 0 deletions test/scripts/processors/post.ts
Original file line number Diff line number Diff line change
Expand Up @@ -805,6 +805,32 @@ describe('post', () => {
]);
});

// use `slug` as `title` of post when `title` is not specified.
// https://github.com/hexojs/hexo/issues/5372
it('post - without title - use filename', async () => {
hexo.config.use_slug_as_post_title = true;

const body = '';

const file = newFile({
path: 'bar.md',
published: true,
type: 'create',
renderable: true
});

await writeFile(file.source, body);
await process(file);
const post = Post.findOne({ source: file.path });

post.title.should.eql('bar');

return Promise.all([
post.remove(),
unlink(file.source)
]);
});

it('post - category is an alias for categories', async () => {
const body = [
'title: "Hello world"',
Expand Down

0 comments on commit 069ac38

Please sign in to comment.