#localization #axum

已删除 axum_l18n

为 Axum 提供本地化工具的 crate

0.1.1 2024年1月2日
0.1.0 2024年1月2日

#54 in #i18n

MIT/Apache

23KB
424 代码行

关于此 Crate

此 crate 提供了一些与 Axum 一起使用的本地化工具。

基本用法

您可以使用此 crate 从请求中提取 语言标识符(例如 en-US)。

如果模式设置为 RedirectMode::NoRedirect,则使用 Accept-Language 标头来查找用户首选的语言。如果模式设置为 RedirectMode::RedirectToFullLocaleSubPathRedirectMode::RedirectToLanguageSubPath,则用户将被重定向到基于其 Accept-Language 标头的子路径,如果不支持则重定向到默认语言。

use unic_langid::{langid, LanguageIdentifier};
use axum::Extension;

pub const ENGLISH: LanguageIdentifier = langid!("en");
pub const JAPANESE: LanguageIdentifier = langid!("ja");

let router = axum::Router::new()
      .route("/lists", get(|Extension(lang): Extension<LanguageIdentifier>|
        async move {
          Html(format!("Your language is: {}", lang.to_string()))
        }))
      .layer(axum_l18n::LanguageIdentifierExtractorLayer::new(
          ENGLISH,
          vec![ENGLISH, JAPANESE],
          axum_l18n::RedirectMode::NoRedirect,
      ));

功能

fluent

启用 fluent 允许您使用 fluent Localizer 添加翻译包。

有关 fluent 和 rust 的详细信息,请参阅 fluent-rs

用法

use unic_langid::{langid, LanguageIdentifier};
use axum_l18n::Localizer;

pub const ENGLISH: LanguageIdentifier = langid!("en");
pub const JAPANESE: LanguageIdentifier = langid!("ja");
let mut localizer = Localizer::new();

localizer
    .add_bundle(JAPANESE, &["locales/ja/main.ftl", "locales/ja/login.ftl"])
    .unwrap();
localizer
    .add_bundle(ENGLISH, &["locales/en/main.ftl", "locales/en/login.ftl"])
    .unwrap();

tera

启用 tera 功能允许您在 tera 模板中使用 fluent 翻译。

有关 tera 的更多信息,请参阅 tera

用法

初始化

use tera::Tera;

let mut tera = Tera::new("src/views/templates/**/*").expect("tera parsing error");

let mut localizer = Localizer::new();

localizer
    .add_bundle(ENGLISH, &["locales/en/main.ftl", "locales/en/login.ftl"])
    .unwrap();

tera.register_function("fluent", localizer);

Axum 处理程序

#[derive(Clone)]
struct ViewRouterState {
    pool: mysql_async::Pool,
    tera: Arc<tera::Tera>,
}

async fn lists_view(
    State(state): State<ViewRouterState>,
    Extension(lang): Extension<LanguageIdentifier>,
) -> axum::response::Response {
    let lists: Vec<String> = List::paginate(&state.pool, claim.sub)
        .await.unwrap();

    let mut ctx = Context::new();
    ctx.insert("lists", &lists);
    ctx.insert("lang", &lang);

    let html = state.tera.render("lists.html", &ctx).unwrap();

    Html(html).into_response()
}

在 tera 模板中

<label for="family-id">{{ fluent(key="list-family", lang=lang) }}</label>
<select name="family-id" id="family-id">
  {% for family in families %}
  <option value="{{ family.family_id }}">{{ family.family_name }}</option>
  {% endfor %}
</select>

依赖关系

~3–13MB
~150K SLoC