73 lines
2.1 KiB
Rust
73 lines
2.1 KiB
Rust
use rocket_dyn_templates::handlebars::{
|
|
Context, Handlebars, Helper, HelperDef, HelperResult, Output, RenderContext, RenderError,
|
|
Renderable,
|
|
};
|
|
|
|
/// Implements an "if_in_list" block helper for string vectors.
|
|
/// Will render true block if one of the parameters 1-x is found in list.
|
|
pub fn in_list_block_helper<'reg, 'rc>(h: &Helper<'reg, 'rc>,
|
|
r: &'reg Handlebars<'reg>,
|
|
ctx: &'rc Context,
|
|
rc: &mut RenderContext<'reg, 'rc>,
|
|
out: &mut dyn Output
|
|
) -> HelperResult{
|
|
let list = h.param(0).unwrap();
|
|
let mut to_find: Vec<&str> = vec![];
|
|
|
|
let mut count: usize = 1;
|
|
loop {
|
|
match h.param(count) {
|
|
None => break,
|
|
Some(val) => {
|
|
match val.value().as_str() {
|
|
Some(value) => to_find.push(value),
|
|
None => {
|
|
return Err(RenderError::new(
|
|
"wrong parameter type. Should be a String.",
|
|
))
|
|
}
|
|
};
|
|
}
|
|
}
|
|
count = count + 1;
|
|
}
|
|
|
|
let list: &Vec<serde_json::Value> = match list.value().as_array() {
|
|
Some(array) => array,
|
|
None => {
|
|
return Err(RenderError::new(
|
|
"wrong parameter type. Should be array/Vec.",
|
|
))
|
|
}
|
|
};
|
|
|
|
let mut found = false;
|
|
|
|
for value in list {
|
|
let string = match value.as_str() {
|
|
Some(string) => string,
|
|
None => {
|
|
return Err(RenderError::new(
|
|
"wrong parameter type. Should be string array/string Vec.",
|
|
))
|
|
}
|
|
};
|
|
|
|
if to_find.contains(&string) {
|
|
found = true;
|
|
break;
|
|
}
|
|
}
|
|
|
|
if found {
|
|
h.template()
|
|
.map(|t| t.render(r, ctx, rc, out))
|
|
.unwrap_or(Ok(()))
|
|
} else {
|
|
//render inverse template (else block), if not found in list.
|
|
h.inverse()
|
|
.map(|t| t.render(r, ctx, rc, out))
|
|
.unwrap_or(Ok(()))
|
|
}
|
|
}
|