Add furigana tera filter

This commit is contained in:
Elnu 2023-07-01 12:36:36 -07:00
parent 981a78f36e
commit a33a05a60a
6 changed files with 52 additions and 5 deletions

View file

@ -21,7 +21,7 @@ use routes::*;
mod i18n;
use i18n::{i18n_filter, load_catalogs};
use crate::i18n::langs_filter;
use crate::{i18n::langs_filter, utils::furigana_filter};
mod prelude;
@ -106,6 +106,12 @@ async fn rocket() -> Result<Rocket<Ignite>, rocket::Error> {
move |value: &Value, args: &HashMap<String, Value>| {
langs_filter(value, args, &langs)
},
);
engines.tera.register_filter(
"furigana",
move |value: &Value, args: &HashMap<String, Value>| {
furigana_filter(value, args)
},
)
}))
.attach(SassFairing::default())

View file

@ -4,7 +4,7 @@ use std::str::FromStr;
use serde::{Deserialize, Deserializer, Serialize};
use serde_yaml::Value;
use crate::prelude::*;
use crate::{prelude::*};
#[derive(Serialize, Deserialize)]
pub struct Challenge {

36
src/utils/furigana.rs Normal file
View file

@ -0,0 +1,36 @@
use std::collections::HashMap;
use regex::Regex;
use rocket_dyn_templates::tera::{self, Value};
pub fn furigana_to_html(text: &str) -> String {
// Original regular expression: \[([^\]]*)\]{([^\}]*)}
// https://regexr.com/6dspa
// https://blog.elnu.com/2022/01/furigana-in-markdown-using-regular-expressions/
// The regex crate users curly braces {} as repetition qualifiers,
// so { needs to be escaped as \{
// Curly brace literals \{ need to have their backslash escaped as \\{
// TODO: Modify so <span lang="ja"> only wraps continuous sections of furigana
let re = Regex::new(r"\[([^\]]*)\]\{([^\\}]*)}").unwrap();
format!("<span lang=\"ja\">{}</span>", re.replace_all(text, "<ruby>$1<rp>(</rp><rt>$2</rt><rp>)</rp></ruby>"))
}
pub fn furigana_filter(value: &Value, _args: &HashMap<String, Value>) -> tera::Result<Value> {
Ok(Value::String(furigana_to_html(value.as_str().expect("The furigana input must be a string"))))
}
#[cfg(test)]
mod tests {
#[test]
fn furigana_to_html() {
use super::furigana_to_html;
assert_eq!(
furigana_to_html("[振]{ふ}り[仮]{が}[名]{な}"),
"<span lang=\"ja\">\
<ruby><rp>(</rp><rt></rt><rp>)</rp></ruby>\
<ruby><rp>(</rp><rt></rt><rp>)</rp></ruby>\
<ruby><rp>(</rp><rt></rt><rp>)</rp></ruby>\
</span>"
);
}
}

View file

@ -5,4 +5,7 @@ mod headers;
pub use headers::*;
mod challenge;
pub use challenge::*;
pub use challenge::*;
mod furigana;
pub use furigana::*;