Rocket 的 rocket_contrib 套件虽然有提供 Template 结构体,可以套用 Handlebars 模板来回应 HTML 数据,但是这些模板文件必须要和程序可执行文件分开来保存才行,所以如果想要实现单档运行的 Web 应用程序,就需要靠其它的方式来使用模板引擎。

先前虽然介绍过把外部文件和 Rust 程序编译在一起的方式,但如果要直接用这样的方式搭配 Rocket 框架,让它能够套用存在于程序可执行文件内部的 Handlebars 模板的话,会遇到一些问题。如果是使用 include_bytes 宏的话,首当其冲会遇到编译速度的问题,这个问题虽然也可以利用该篇文章介绍的「Lazy Static Include」套件获得缓解,但还有个大问题是依然存在的。

Rocket 应用程序所使用的 Handlebars 模板,在开发阶段时也会跟着 Rust 程序不断进行修改。如果将这些模板文件编译进程式可执行文件中,那么每当这些文件被修改后,总是要重新编译并重新运行 Rocket 应用程序才能看到修改后的结果,进而严重拖慢开发速度。

Include Handlebars Templates for Rocket Framework

「Include Handlebars Templates for Rocket Framework」是笔者开发的套件,是针对上述问题提出的解决方案。在非使用 release 模式来编译程序项目时,这个套件不会将 Handlebars 的模板文件与 Rust 程序编译在一起,取而代之的是,将其读取到内存中,并且在 Rocket 框架接收到 HTTP 请求时,依照所有模板文件的修改日期来判断模板引擎是否需要重新加载这些模板。这个套件也能够将产生出来的 HTML 语法压缩或是缓存起来,除此之外还提供了 HTTP 的 ETag 机制。

Crates.io

Cargo.toml

rocket-include-handlebars = "*"

使用方法

rocket_include_handlebars 这个 crate 提供了 HandlebarsResponse 结构体,可以直接作为路由处理程序的函数回传值的类型。在使用这个套件时,首先要用 HandlebarsResponse 结构体提供的 fairing 关联函数来产生整流片,并注册给 Rocket 来使用,这个整流片可以在 Rocket 应用程序状态中创建一个大小为 64(笔)的缓存空间。fairing 关联函数必须传入一个闭包,在这个闭包中,必须使用 rocket_include_handlebars 这个 crate 提供的 handlebars_resources_initialize 宏,来设置要一同编译进 Rust 程序的 Handlebars 模板文件,而其设置的方式为:先指定模板文件的键值,再指定模板文件的路径。在路由处理程序中,可以使用同样由 rocket_include_handlebars 这个 crate 提供的 handlebars_response 宏,传入要回应的模板文件的键值和上下文(context),就可以产生出对应的 HandlebarsResponse 结构实体。

预设的 handlebars_response 宏所产生出来的 HandlebarsResponse 结构实体会主动压缩 HTML 语法,如果不想要压缩 HTML 语法的话,可以在第一个参数前加上 disable_minify。如果只想要在 release 模式下才压缩 HTML 语法的话,可以在第一个参数前加上 auto_minify。

如果要缓存产生出来的 HandlebarsResponse 结构实体,可以再使用 rocket_include_handlebars 这个 crate 提供的 handlebars_response_cache 宏。使用 handlebars_response_cache 宏时,要去取得被注册在 Rocket 应用程序状态中的 HandlebarsContextManager。

举例来说,在 Cargo 程序项目的根目录底下的 views 目录中,有 index.hbs 和 index2.hbs 这两个 Handlebars 模板,若要使 Rocket 应用程序能够套用这两个模板文件,并且使这两个文件能跟可执行文件编译在一起的话,程序可以写成以下这样:

#[macro_use]
extern crate rocket;

#[macro_use]
extern crate rocket_include_handlebars;

use std::collections::HashMap;

use rocket::State;
use rocket_include_handlebars::{EtagIfNoneMatch, HandlebarsContextManager, HandlebarsResponse};
use serde_json::json;

#[get("/")]
fn index(
    handlebars_cm: &State<HandlebarsContextManager>,
    etag_if_none_match: EtagIfNoneMatch,
) -> HandlebarsResponse {
    let mut map = HashMap::new();

    map.insert("title", "Title");
    map.insert("body", "Hello, world!");

    handlebars_response!(handlebars_cm, etag_if_none_match, "index", map)
}

#[get("/disable-minify")]
fn index_disable_minify(
    handlebars_cm: &State<HandlebarsContextManager>,
    etag_if_none_match: EtagIfNoneMatch,
) -> HandlebarsResponse {
    let mut map = HashMap::new();

    map.insert("title", "Title");
    map.insert("body", "Hello, world!");

    handlebars_response!(disable_minify handlebars_cm, etag_if_none_match, "index", map)
}

#[get("/2")]
fn index_2(
    cm: &State<HandlebarsContextManager>,
    etag_if_none_match: EtagIfNoneMatch,
) -> HandlebarsResponse {
    handlebars_response_cache!(cm, etag_if_none_match, "index-2", {
        println!("Generate index-2 and cache it...");

        let json = json! ({
            "title": "Title",
            "placeholder": "Hello, \"world!\"",
            "id": 0,
        });

        handlebars_response!(auto_minify cm, EtagIfNoneMatch::default(), "index2", json)
    })
}

#[launch]
fn rocket() -> _ {
    rocket::build()
        .attach(HandlebarsResponse::fairing(|handlebars| {
            handlebars_resources_initialize!(
                handlebars,
                "index" => "views/index.hbs",
                "index2" => ("views", "index2.hbs")
            );

            handlebars_helper!(inc: |x: i64| x + 1);

            handlebars.register_helper("inc", Box::new(inc));

            // NOTE: The above `inc` helper can be alternately added by enabling the `helper_inc` feature for the rocket_include_handlebars crate.
        }))
        .mount("/", routes![index, index_disable_minify])
        .mount("/", routes![index_2])
}

这边要注意的是,在传给 HandlebarsResponse 结构体的 fairing 关联函数使用的闭包中,我们替 handlebars 变量注册了我们自订的 helper 函数。以下是 index.hbs 和 index2.hbs 的源代码,可以参考一下:

<!DOCTYPE html>
<html>
<head>
    <meta charset=UTF-8>
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>{{title}}</title>
</head>
<body>
{{body}}
</body>
<!DOCTYPE html>
<html>
<head>
    <meta charset=UTF-8>
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>{{title}}</title>
</head>
<body>
<input id="input-{{inc id}}" type="text" placeholder="{{placeholder}}">
</body>

实际上,这个套件已经有替 Handlebars 模板引擎提供一些内置的额外 helper 函数,可以在 Cargo.toml 设置档中激活以下特色来直接引用有需要的 helper 函数,就不用自己再写一次啦!

  • helper_inc:激活 inc 函数,可以使数值加一。
  • helper_dec:激活 dec 函数,可以使数值减一。
  • helper_eq_str:激活 eq_str 函数,可以判断两个字符串是否相同。
  • helper_ne_str:激活 ne_str 函数,可以判断两个字符串是否不相同。

如果觉得预设的缓存空间太小的话,可以使用 HandlebarsResponse 结构体的 fairing_cache 关联函数来产生整流片,这个 fairing_cache 关联函数传入的闭包可以直接回传要在应用程序状态中创建的缓存空间大小。

例如:

rocket::build()
    .attach(HandlebarsResponse::fairing_cache(|handlebars| {
        handlebars_resources_initialize!(
            handlebars,
            "index" => "views/index.hbs",
            "index2" => ("views", "index2.hbs")
        );

        handlebars_helper!(inc: |x: i64| x + 1);

        handlebars.register_helper("inc", Box::new(inc));

        512
    }))