Updated the call site for handlebars rendering

This commit is contained in:
Michael Bryan 2018-03-14 23:28:32 +08:00
parent 951c873df6
commit 867fbfec05
No known key found for this signature in database
GPG Key ID: E9C602B0D9A998DC
2 changed files with 80 additions and 77 deletions

View File

@ -4,7 +4,6 @@ use std::collections::BTreeMap;
use serde_json; use serde_json;
use handlebars::{Context, Handlebars, Helper, RenderContext, RenderError, Renderable}; use handlebars::{Context, Handlebars, Helper, RenderContext, RenderError, Renderable};
type StringMap = BTreeMap<String, String>; type StringMap = BTreeMap<String, String>;
/// Target for `find_chapter`. /// Target for `find_chapter`.
@ -15,7 +14,8 @@ enum Target {
impl Target { impl Target {
/// Returns target if found. /// Returns target if found.
fn find(&self, fn find(
&self,
base_path: &String, base_path: &String,
current_path: &String, current_path: &String,
current_item: &StringMap, current_item: &StringMap,
@ -23,14 +23,14 @@ impl Target {
) -> Result<Option<StringMap>, RenderError> { ) -> Result<Option<StringMap>, RenderError> {
match self { match self {
&Target::Next => { &Target::Next => {
let previous_path = previous_item.get("path").ok_or_else(|| { let previous_path = previous_item
RenderError::new("No path found for chapter in JSON data") .get("path")
})?; .ok_or_else(|| RenderError::new("No path found for chapter in JSON data"))?;
if previous_path == base_path { if previous_path == base_path {
return Ok(Some(current_item.clone())); return Ok(Some(current_item.clone()));
} }
}, }
&Target::Previous => { &Target::Previous => {
if current_path == base_path { if current_path == base_path {
@ -43,18 +43,15 @@ impl Target {
} }
} }
fn find_chapter( fn find_chapter(rc: &mut RenderContext, target: Target) -> Result<Option<StringMap>, RenderError> {
rc: &mut RenderContext,
target: Target
) -> Result<Option<StringMap>, RenderError> {
debug!("Get data from context"); debug!("Get data from context");
let chapters = rc.evaluate_absolute("chapters").and_then(|c| { let chapters = rc.evaluate_absolute("chapters", true).and_then(|c| {
serde_json::value::from_value::<Vec<StringMap>>(c.clone()) serde_json::value::from_value::<Vec<StringMap>>(c.clone())
.map_err(|_| RenderError::new("Could not decode the JSON data")) .map_err(|_| RenderError::new("Could not decode the JSON data"))
})?; })?;
let base_path = rc.evaluate_absolute("path")? let base_path = rc.evaluate_absolute("path", true)?
.as_str() .as_str()
.ok_or_else(|| RenderError::new("Type error for `path`, string expected"))? .ok_or_else(|| RenderError::new("Type error for `path`, string expected"))?
.replace("\"", ""); .replace("\"", "");
@ -91,14 +88,17 @@ fn render(
let mut context = BTreeMap::new(); let mut context = BTreeMap::new();
chapter.get("name") chapter
.get("name")
.ok_or_else(|| RenderError::new("No title found for chapter in JSON data")) .ok_or_else(|| RenderError::new("No title found for chapter in JSON data"))
.map(|name| context.insert("title".to_owned(), json!(name)))?; .map(|name| context.insert("title".to_owned(), json!(name)))?;
chapter.get("path") chapter
.get("path")
.ok_or_else(|| RenderError::new("No path found for chapter in JSON data")) .ok_or_else(|| RenderError::new("No path found for chapter in JSON data"))
.and_then(|p| { .and_then(|p| {
Path::new(p).with_extension("html") Path::new(p)
.with_extension("html")
.to_str() .to_str()
.ok_or_else(|| RenderError::new("Link could not be converted to str")) .ok_or_else(|| RenderError::new("Link could not be converted to str"))
.map(|p| context.insert("link".to_owned(), json!(p.replace("\\", "/")))) .map(|p| context.insert("link".to_owned(), json!(p.replace("\\", "/"))))
@ -169,8 +169,9 @@ mod tests {
h.register_helper("next", Box::new(next)); h.register_helper("next", Box::new(next));
assert_eq!( assert_eq!(
h.template_render(TEMPLATE, &data).unwrap(), h.render_template(TEMPLATE, &data).unwrap(),
"one: one.html|three: three.html"); "one: one.html|three: three.html"
);
} }
#[test] #[test]
@ -199,8 +200,9 @@ mod tests {
h.register_helper("next", Box::new(next)); h.register_helper("next", Box::new(next));
assert_eq!( assert_eq!(
h.template_render(TEMPLATE, &data).unwrap(), h.render_template(TEMPLATE, &data).unwrap(),
"|two: two.html"); "|two: two.html"
);
} }
#[test] #[test]
fn test_last() { fn test_last() {
@ -228,7 +230,8 @@ mod tests {
h.register_helper("next", Box::new(next)); h.register_helper("next", Box::new(next));
assert_eq!( assert_eq!(
h.template_render(TEMPLATE, &data).unwrap(), h.render_template(TEMPLATE, &data).unwrap(),
"two: two.html|"); "two: two.html|"
);
} }
} }

View File

@ -8,7 +8,7 @@ use pulldown_cmark::{html, Event, Parser, Tag};
// Handlebars helper to construct TOC // Handlebars helper to construct TOC
#[derive(Clone, Copy)] #[derive(Clone, Copy)]
pub struct RenderToc { pub struct RenderToc {
pub no_section_label: bool pub no_section_label: bool,
} }
impl HelperDef for RenderToc { impl HelperDef for RenderToc {
@ -16,11 +16,11 @@ impl HelperDef for RenderToc {
// get value from context data // get value from context data
// rc.get_path() is current json parent path, you should always use it like this // rc.get_path() is current json parent path, you should always use it like this
// param is the key of value you want to display // param is the key of value you want to display
let chapters = rc.evaluate_absolute("chapters").and_then(|c| { let chapters = rc.evaluate_absolute("chapters", true).and_then(|c| {
serde_json::value::from_value::<Vec<BTreeMap<String, String>>>(c.clone()) serde_json::value::from_value::<Vec<BTreeMap<String, String>>>(c.clone())
.map_err(|_| RenderError::new("Could not decode the JSON data")) .map_err(|_| RenderError::new("Could not decode the JSON data"))
})?; })?;
let current = rc.evaluate_absolute("path")? let current = rc.evaluate_absolute("path", true)?
.as_str() .as_str()
.ok_or_else(|| RenderError::new("Type error for `path`, string expected"))? .ok_or_else(|| RenderError::new("Type error for `path`, string expected"))?
.replace("\"", ""); .replace("\"", "");
@ -107,10 +107,10 @@ impl HelperDef for RenderToc {
// filter all events that are not inline code blocks // filter all events that are not inline code blocks
let parser = Parser::new(name).filter(|event| match *event { let parser = Parser::new(name).filter(|event| match *event {
Event::Start(Tag::Code) | Event::Start(Tag::Code)
Event::End(Tag::Code) | | Event::End(Tag::Code)
Event::InlineHtml(_) | | Event::InlineHtml(_)
Event::Text(_) => true, | Event::Text(_) => true,
_ => false, _ => false,
}); });