Add post title
This commit is contained in:
@@ -1,5 +1,5 @@
|
||||
use chrono::{DateTime, Utc};
|
||||
use pulldown_cmark::{html, Options, Parser};
|
||||
use pulldown_cmark::{html, Event, HeadingLevel, Options, Parser, Tag};
|
||||
use std::collections::HashMap;
|
||||
use std::fs;
|
||||
use std::path::PathBuf;
|
||||
@@ -8,6 +8,7 @@ use std::process::Command;
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Post {
|
||||
pub name: String,
|
||||
pub title: String,
|
||||
#[allow(dead_code)]
|
||||
pub filename: String,
|
||||
#[allow(dead_code)]
|
||||
@@ -143,9 +144,10 @@ impl PostManager {
|
||||
}
|
||||
let markdown_content = fs::read_to_string(&entry.file_path)
|
||||
.map_err(|e| format!("Failed to read post file: {}", e))?;
|
||||
let html_content = markdown_to_html(&markdown_content);
|
||||
let (html_content, title) = markdown_to_html(&markdown_content);
|
||||
let post = Post {
|
||||
name: name.clone(),
|
||||
title: title,
|
||||
filename: entry.file_path,
|
||||
markdown_content,
|
||||
html_content,
|
||||
@@ -189,7 +191,28 @@ impl PostManager {
|
||||
}
|
||||
}
|
||||
|
||||
fn markdown_to_html(markdown: &str) -> String {
|
||||
fn markdown_title(markdown: &str) -> Option<String> {
|
||||
let parser = Parser::new(markdown);
|
||||
for event in parser {
|
||||
if let Event::Start(tag) = event {
|
||||
if let Tag::Heading {
|
||||
level,
|
||||
id,
|
||||
..
|
||||
} = tag
|
||||
{
|
||||
if level == HeadingLevel::H1 {
|
||||
if let Some(str) = id {
|
||||
return Some(str.to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn markdown_to_html(markdown: &str) -> (String, String) {
|
||||
let mut options = Options::empty();
|
||||
options.insert(Options::ENABLE_STRIKETHROUGH);
|
||||
options.insert(Options::ENABLE_TABLES);
|
||||
@@ -197,8 +220,10 @@ fn markdown_to_html(markdown: &str) -> String {
|
||||
options.insert(Options::ENABLE_TASKLISTS);
|
||||
options.insert(Options::ENABLE_SMART_PUNCTUATION);
|
||||
|
||||
let title = markdown_title(markdown).unwrap_or("unknown".to_string());
|
||||
|
||||
let parser = Parser::new_ext(markdown, options);
|
||||
let mut html_output = String::new();
|
||||
html::push_html(&mut html_output, parser);
|
||||
html_output
|
||||
(html_output, title)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user