1
0
Fork 0

Add helper "translate"

This commit is contained in:
Alex Kotov 2020-10-24 19:53:53 +05:00
parent 3d76923802
commit a4c7d610a3
Signed by: kotovalexarian
GPG Key ID: 553C0EBBEB5D5F08
6 changed files with 66 additions and 4 deletions

1
Cargo.lock generated
View File

@ -309,6 +309,7 @@ dependencies = [
"diesel",
"dotenv",
"fluent-bundle",
"handlebars",
"r2d2",
"regex",
"rocket",

View File

@ -16,6 +16,7 @@ publish = true
bcrypt = "0.8.2"
dotenv = "0.15.0"
fluent-bundle = "0.13.1"
handlebars = "1.1.0"
r2d2 = "0.8.9"
regex = "1.4.1"
rocket_csrf = "0.2.0"

View File

@ -1,3 +1,5 @@
pub mod handlebars_helpers;
use std::collections::HashMap;
use fluent_bundle::{FluentError, FluentResource};

View File

@ -0,0 +1,44 @@
use super::I18n;
use handlebars::{
Context,
Handlebars,
Helper,
HelperDef,
HelperResult,
Output,
RenderContext,
RenderError,
};
pub fn translate(i18n: std::sync::Arc<I18n>) -> Box<dyn HelperDef> {
Box::new(move |
helper: &Helper,
_: &Handlebars,
_: &Context,
_: &mut RenderContext,
output: &mut dyn Output,
| -> HelperResult {
let locale = helper.param(0)
.ok_or(RenderError::new("expected locale param"))?
.value().as_str()
.ok_or(RenderError::new("expected locale param"))?;
let key = helper.param(1)
.ok_or(RenderError::new("expected key param"))?
.value().as_str()
.ok_or(RenderError::new("expected key param"))?;
let i18n = i18n.clone();
let l10n = i18n.l10n(locale).ok()
.ok_or(RenderError::new("unknown locale"))?;
let translated = l10n.translate(key).ok()
.ok_or(RenderError::new("translation error"))?;
output.write(&translated)?;
Ok(())
})
}

View File

@ -1,6 +1,6 @@
use crate::config;
use crate::database;
use crate::i18n::I18n;
use crate::i18n::{self, I18n};
use crate::routes;
use rocket_contrib::serve::{Options as ServeOptions, StaticFiles};
@ -17,12 +17,24 @@ pub fn rocket(config: &config::Config) -> Result<rocket::Rocket, ()> {
Ok(i18n) => i18n,
};
let i18n_arc = match I18n::new(&locales_path, &["en", "ru"]) {
Err(_) => return Err(()),
Ok(i18n) => std::sync::Arc::new(i18n),
};
let result = rocket::custom(rocket_config)
.manage(i18n)
.manage(database::create_db_pool(config))
.attach(rocket_csrf::Fairing::new())
.attach(Template::custom(|engines| {
.attach(Template::custom(move |engines| {
engines.handlebars.set_strict_mode(true);
let i18n_arc = i18n_arc.clone();
engines.handlebars.register_helper(
"translate",
i18n::handlebars_helpers::translate(i18n_arc),
);
}))
.mount("/", routes::routes())
.mount("/", StaticFiles::new(public_path, ServeOptions::None));

View File

@ -1,6 +1,8 @@
<div class="jumbotron jumbotron-fluid text-center">
<div class="container">
<h1>{{ i18n_fedihub }}</h1>
<p class="lead">{{ i18n_federated_services_without_censorship }}</p>
<h1>{{ translate "en" "fedihub" }}</h1>
<p class="lead">
{{ translate "en" "federated-services-without-censorship" }}
</p>
</div>
</div>