-
-
Notifications
You must be signed in to change notification settings - Fork 136
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Get Array Length #43
Comments
Considering |
In rust we only have a JavaScript type system, but no expression support built-in. Currently you can use a helper like this (not tested, need error check): // implement via bare function
fn alength_helper (c: &Context, h: &Helper, _: &Handlebars, rc: &mut RenderContext) -> Result<(), RenderError> {
let param = h.params().get(0).unwrap();
let value = c.navigate(rc.get_path(), param);
try!(rc.writer.write(value.as_array().unwrap().len().to_string().into_bytes().as_ref()));
Ok(())
} Supporting these special properties like |
It's still true that Here is a version of the helper that works with current Rust/Handlebars/Serde, in case someone else also finds this issue on GitHub, and this can be useful to them. This version follows what seems to otherwise be Handlebars standard of outputting nothing if the input didn't make sense, and not panicing. use rocket_contrib::handlebars::{Handlebars, Helper, RenderContext, RenderError};
use serde_json::value::Value;
type HelperResult = Result<(), RenderError>;
pub fn length_helper(h: &Helper, _: &Handlebars, rc: &mut RenderContext) -> HelperResult {
if let Some(param) = h.param(0) {
let param = param.value();
if let &Value::Array(ref array) = param {
rc.writer
.write(array.len().to_string().into_bytes().as_ref())?;
}
}
Ok(())
} |
@csirkeee is RenderContext from rocket_contrib crate?
|
@nnovakov-alexey it says handlebars not available from rocket_contrib, did you have handlebars feature turned on when importing rocket_contrib? |
@sunng87 yes, exactly.
|
@novakov-alexey as of 1.0, there is no Rocket contrib 0.3.16 was using handlebars 0.x version, and it will conflict with 1.0. I suggest you to use git version, or remote explicit |
Answering my question as for helper to get array length using standalone handlebars crate:
Cargo.toml Usage:
|
Handlebars support accessing an array length:
(For instance see http://stackoverflow.com/questions/15428584/how-to-find-array-length-inside-the-handlebar-templates)
It seems this is currently not supported in handlebars-rust.
The workaround I used was to add a
length
custom helper (candidate for built-in helpers?), but maybe following the original syntax would also be a good idea?The text was updated successfully, but these errors were encountered: