Помощники руля в ракете (ржавчина) - PullRequest
0 голосов
/ 02 августа 2020

Я изучаю ржавчину, и я наткнулся на проблему, которую не могу решить.

Я пытаюсь зарегистрировать помощника для руля, конечная цель - иметь помощника, который вычисляет / печатает длину Vec. Но мне уже не удается получить образцы из документации в свою программу. Мне удалось сделать «минимальный» пример, который показывает ту же ошибку, что и моя страница ракеты.

#[macro_use]
extern crate handlebars;

extern crate rocket;
extern crate rocket_contrib;

use handlebars::{Context, Handlebars, Helper, HelperResult, JsonRender, Output, RenderContext};
use rocket_contrib::templates::Template;

handlebars_helper!(hex: |v: i64| format!("0x{:x}", v));

fn wow_helper(
    h: &Helper,
    _: &Handlebars,
    _: &Context,
    _: &mut RenderContext,
    out: &mut Output,
) -> HelperResult {
    if let Some(param) = h.param(0) {
        out.write("<b><i>")?;
        out.write(&param.value().render())?;
        out.write("</b></i>")?;
    }

    Ok(())
}

fn main() {
    rocket::ignite()
        .attach(Template::custom(|engines| {
            engines
                .handlebars
                .register_helper("mlenb", Box::new(wow_helper));
        }))
        .launch();
    println!("Hello, world!");
}

с зависимостями в cargo.toml:

[dependencies]
handlebars="3.3.0"
rocket="0.4.5"

[dependencies.rocket_contrib]
version = "0.4.5"
default-features = false
features = ["diesel_sqlite_pool", "handlebars_templates", "serve"]

Ошибка:

error[E0631]: type mismatch in function arguments
   --> src/main.rs:184:43
    |
162 | / fn wow_helper(
163 | |     h: &handlebars::Helper,
164 | |     _: &handlebars::Handlebars,
165 | |     _: &handlebars::Context,
...   |
175 | |     Ok(())
176 | | }
    | |_- found signature of `for<'r, 's, 't0, 't1, 't2, 't3, 't4, 't5, 't6, 't7> fn(&'r handlebars::Helper<'s, 't0>, &'t1 handlebars::Handlebars<'t2>, &'t3 handlebars::Context, &'t4 mut handlebars::RenderContext<'t5, 't6>, &'t7 mut (dyn handlebars::Output + 't7)) -> _`
...
184 |                   .register_helper("mlenb", Box::new(wow_helper));
    |                                             ^^^^^^^^^^^^^^^^^^^^ expected signature of `for<'r, 'reg, 'rc, 's, 't0> fn(&'r rocket_contrib::templates::handlebars::Helper<'reg, 'rc>, &'reg rocket_contrib::templates::handlebars::Handlebars, &'rc rocket_contrib::templates::handlebars::Context, &'s mut rocket_contrib::templates::handlebars::RenderContext<'reg>, &'t0 mut (dyn rocket_contrib::templates::handlebars::Output + 't0)) -> _`
    |
    = note: required because of the requirements on the impl of `rocket_contrib::templates::handlebars::HelperDef` for `for<'r, 's, 't0, 't1, 't2, 't3, 't4, 't5, 't6, 't7> fn(&'r handlebars::Helper<'s, 't0>, &'t1 handlebars::Handlebars<'t2>, &'t3 handlebars::Context, &'t4 mut handlebars::RenderContext<'t5, 't6>, &'t7 mut (dyn handlebars::Output + 't7)) -> std::result::Result<(), handlebars::RenderError> {wow_helper}`
    = note: required for the cast to the object type `dyn rocket_contrib::templates::handlebars::HelperDef`

Спасибо за вашу помощь, мы очень ценим это!

1 Ответ

0 голосов
/ 04 августа 2020

Благодаря @jebrosen: mozilla.org в канале rocket matrix проблема решена.

Проблема:

Я использовал несовместимые версии руля. Библиотека ракеты использует версию 1.0, в то время как я использовал версию 3.0 в Cargo.toml.

Решение:

Измените Cargo.toml на:

[dependencies]
handlebars="1.0"
rocket="0.4.5"

[dependencies.rocket_contrib]
version = "0.4.5"
default-features = false
features = ["diesel_sqlite_pool", "handlebars_templates", "serve"]

Осторожно перестройте требуется cargo clean, иначе изменения не будут внесены.

Решение исходной проблемы:

Мне не удалось использовать макрос handlebars_helper! для создания помощника длины, а вместо этого создал его с использованием синтаксиса функции.

fn mlen_helper_fun(
    h: &handlebars::Helper<'_, '_>,
    _: &handlebars::Handlebars,
    _: &handlebars::Context,
    _: &mut handlebars::RenderContext<'_>,
    out: &mut dyn handlebars::Output,
) -> handlebars::HelperResult {
    if let Some(param) = h.param(0) {
        if let serde_json::value::Value::Array(arr) = param.value() {
            out.write(&format!("{}", arr.len()))?;
            Ok(())
        } else {
            Err(handlebars::RenderError::new("Not a array"))
        }
    } else {
        Err(handlebars::RenderError::new(
            "No parameter given at least one required",
        ))
    }
}

Затем его можно использовать с:


        .attach(Template::custom(|engines| {
            engines
                .handlebars
                .register_helper("length", Box::new(mlen_helper_fun));
        }))
...