GithubHelp home page GithubHelp logo

Get Array Length about handlebars-rust HOT 9 CLOSED

sunng87 avatar sunng87 commented on May 13, 2024
Get Array Length

from handlebars-rust.

Comments (9)

novakov-alexey-zz avatar novakov-alexey-zz commented on May 13, 2024 1

Answering my question as for helper to get array length using standalone handlebars crate:

extern crate handlebars;
use handlebars::*;

pub fn array_length_helper(
    h: &Helper,
    _: &Handlebars,
    _: &Context,
    _: &mut RenderContext,
    out: &mut Output,
) -> Result<(), RenderError> {
    let length = h
        .param(0)
        .as_ref()
        .and_then(|v| v.value().as_array())
        .map(|arr| arr.len())
        .ok_or(RenderError::new(
            "Param 0 with 'array' type is required for array_length helper",
        ))?;

    out.write(length.to_string().as_ref())?;

    Ok(())
}

Cargo.toml
handlebars = "1.0.4"

Usage:

{{#each fields as |field| ~}}
        <tr>
          {{#if (lt @index 1)}}
            <td valign="top" class="td3" rowspan="{{array_length ../fields}}">
.....

from handlebars-rust.

gyscos avatar gyscos commented on May 13, 2024

Considering context::navigate returns a &Json, it'll be hard to have it return the length. I guess changing the function to return a Cow would be a solution, but I'm not sure it's super convenient...

from handlebars-rust.

sunng87 avatar sunng87 commented on May 13, 2024

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 length in context.navigate is also a good idea. But we may need to implement all javascript native properties. Currently I have no idea about how much work it needs.

from handlebars-rust.

csirkeee avatar csirkeee commented on May 13, 2024

It's still true that length doesn't work in Rust Handlebars, and works in the original JS Handlebars. The helper that was posted here by @sunng87 only worked with earlier versions of the library. Since then, the helper method signature changed, and Handlebars switched to Serde, so I had to make some modifications.

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(())
}

from handlebars-rust.

novakov-alexey-zz avatar novakov-alexey-zz commented on May 13, 2024

@csirkeee is RenderContext from rocket_contrib crate?
if I use RenderContext directly from extern crate handlebars, I am missing writer field in it. I am wondering if this struct is evolved since then. However, there is handlebars module at rocker_contrib version=0.3.16

6 | use self::rocket_contrib::handlebars::{Handlebars, Helper, RenderContext, RenderError};
  |                           ^^^^^^^^^^ Could not find `handlebars` in `rocket_contrib`

from handlebars-rust.

sunng87 avatar sunng87 commented on May 13, 2024

@nnovakov-alexey it says handlebars not available from rocket_contrib, did you have handlebars feature turned on when importing rocket_contrib?

from handlebars-rust.

novakov-alexey-zz avatar novakov-alexey-zz commented on May 13, 2024

@sunng87 yes, exactly.

extern crate rocket_contrib;
use rocket_contrib::handlebars::{Handlebars, Helper, RenderContext, RenderError};

rocket_contrib = {version="0.3.16", features = ["handlebars_templates"]}
I am also using hanlebars explicitly for my project in toml file:
handlebars = "1.0.4"

from handlebars-rust.

sunng87 avatar sunng87 commented on May 13, 2024

@novakov-alexey as of 1.0, there is no writer in RenderContext any more. Use the Output to write bytes.

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 handlebars = 1.0.4 to see if it would work.

from handlebars-rust.

novakov-alexey-zz avatar novakov-alexey-zz commented on May 13, 2024

@sunng87 thanks for advice. Yes, I am using remote explicit handlebars = 1.0.4.
Actually, I am trying to make @csirkeee example above working with standalone handlebars. @sunng87 which Output do you mean please? :-) I am quite new to Rust ecosystem.

from handlebars-rust.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.