🌐 Change to LANGID_DEFAULT name and update docs

This commit is contained in:
Manuel Cillero 2024-02-27 17:45:54 +01:00
parent e011cf7f62
commit 2cd1d1332c
4 changed files with 54 additions and 40 deletions

View file

@ -45,8 +45,8 @@ impl Application {
// Starts logging and event tracing. // Starts logging and event tracing.
LazyStatic::force(&trace::TRACING); LazyStatic::force(&trace::TRACING);
// Validates the global language identifier. // Validates the default language identifier.
LazyStatic::force(&locale::LANGID); LazyStatic::force(&locale::LANGID_DEFAULT);
#[cfg(feature = "database")] #[cfg(feature = "database")]
// Connects to the database. // Connects to the database.

View file

@ -12,13 +12,32 @@ impl PackageTrait for Welcome {
} }
fn configure_service(&self, scfg: &mut service::web::ServiceConfig) { fn configure_service(&self, scfg: &mut service::web::ServiceConfig) {
scfg.route("/", service::web::get().to(demo)); scfg.route("/", service::web::get().to(home_page))
.route("/{lang}", service::web::get().to(home_lang));
} }
} }
async fn demo(request: service::HttpRequest) -> ResultPage<Markup, ErrorPage> { async fn home_page(request: service::HttpRequest) -> ResultPage<Markup, ErrorPage> {
home(request, &LANGID_DEFAULT)
}
async fn home_lang(
request: service::HttpRequest,
path: service::web::Path<String>,
) -> ResultPage<Markup, ErrorPage> {
match langid_for(path.into_inner()) {
Ok(lang) => home(request, lang),
_ => Err(ErrorPage::NotFound(request)),
}
}
fn home(
request: service::HttpRequest,
lang: &'static LanguageIdentifier,
) -> ResultPage<Markup, ErrorPage> {
Page::new(request) Page::new(request)
.with_title(L10n::l("welcome_title")) .with_title(L10n::l("welcome_title"))
.with_context(ContextOp::LangId(lang))
.with_context(ContextOp::AddStyleSheet(StyleSheet::at( .with_context(ContextOp::AddStyleSheet(StyleSheet::at(
"/base/css/welcome.css", "/base/css/welcome.css",
))) )))

View file

@ -2,7 +2,7 @@ use crate::base::component::add_base_assets;
use crate::core::theme::all::{theme_by_single_name, THEME}; use crate::core::theme::all::{theme_by_single_name, THEME};
use crate::core::theme::ThemeRef; use crate::core::theme::ThemeRef;
use crate::html::{html, Assets, HeadScript, HeadStyles, JavaScript, Markup, StyleSheet}; use crate::html::{html, Assets, HeadScript, HeadStyles, JavaScript, Markup, StyleSheet};
use crate::locale::{LanguageIdentifier, LANGID}; use crate::locale::{LanguageIdentifier, LANGID_DEFAULT};
use crate::service::HttpRequest; use crate::service::HttpRequest;
use crate::{concat_string, util}; use crate::{concat_string, util};
@ -46,7 +46,7 @@ impl Context {
pub(crate) fn new(request: HttpRequest) -> Self { pub(crate) fn new(request: HttpRequest) -> Self {
Context { Context {
request, request,
langid : &LANGID, langid : &LANGID_DEFAULT,
theme : *THEME, theme : *THEME,
stylesheet: Assets::<StyleSheet>::new(), // Stylesheets. stylesheet: Assets::<StyleSheet>::new(), // Stylesheets.
headstyles: Assets::<HeadStyles>::new(), // Styles in head. headstyles: Assets::<HeadStyles>::new(), // Styles in head.

View file

@ -1,22 +1,21 @@
//! Localization (L10n). //! Localization (L10n).
//! //!
//! PageTop usa el conjunto de especificaciones [Fluent](https://www.projectfluent.org/) para la //! PageTop uses the [Fluent](https://www.projectfluent.org/) set of specifications for application
//! localización de aplicaciones. //! localization.
//! //!
//! # Sintaxis Fluent (FTL) //! # Fluent Syntax (FTL)
//! //!
//! El formato utilizado para describir los recursos de traducción utilizados por Fluent se llama //! The format used to describe the translation resources used by Fluent is called
//! [FTL](https://www.projectfluent.org/fluent/guide/). FTL está diseñado para ser fácil de leer, //! [FTL](https://www.projectfluent.org/fluent/guide/). FTL is designed to be easy to read while
//! pero al mismo tiempo permite representar conceptos complejos del lenguaje natural para tratar //! simultaneously allowing the representation of complex natural language concepts to address
//! género, plurales, conjugaciones, y otros. //! gender, plurals, conjugations, and others.
//! //!
//! # Fluent Resources
//! //!
//! # Recursos Fluent //! PageTop utilizes [fluent-templates](https://docs.rs/fluent-templates/) to integrate localization
//! //! resources into the application binary. The following example groups files and subfolders from
//! PageTop usa [fluent-templates](https://docs.rs/fluent-templates/) para integrar los recursos de //! *src/locale* that have a valid [Unicode Language Identifier](https://docs.rs/unic-langid/) and
//! localización en el binario de la aplicación. El siguiente ejemplo agrupa archivos y subcarpetas //! assigns them to their corresponding identifier:
//! de *src/locale* que tienen un [Identificador de Idioma Unicode](https://docs.rs/unic-langid/)
//! válido y los asigna a su identificador correspondiente:
//! //!
//! ```text //! ```text
//! src/locale/ //! src/locale/
@ -35,7 +34,7 @@
//! └── main.ftl //! └── main.ftl
//! ``` //! ```
//! //!
//! Ejemplo de un archivo *src/locale/en-US/main.ftl*: //! Example of a file *src/locale/en-US/main.ftl*:
//! //!
//! ```text //! ```text
//! hello-world = Hello world! //! hello-world = Hello world!
@ -51,7 +50,7 @@
//! }. //! }.
//! ``` //! ```
//! //!
//! Ejemplo del archivo equivalente *src/locale/es-ES/main.ftl*: //! Example of the equivalent file *src/locale/es-ES/main.ftl*:
//! //!
//! ```text //! ```text
//! hello-world = Hola mundo! //! hello-world = Hola mundo!
@ -67,11 +66,11 @@
//! }. //! }.
//! ``` //! ```
//! //!
//! # Cómo aplicar la localización en tu código //! # How to apply localization in your code
//! //!
//! Una vez hayas creado tu directorio de recursos FTL usa la macro //! Once you have created your FTL resource directory, use the
//! [`static_locales!`](crate::static_locales) para integrarlos en tu módulo o aplicación. //! [`static_locales!`](crate::static_locales) macro to integrate them into your module or
//! si tus recursos se encuentran en el directorio `"src/locale"` bastará con declarar: //! application. If your resources are located in the `"src/locale"` directory, simply declare:
//! //!
//! ``` //! ```
//! use pagetop::prelude::*; //! use pagetop::prelude::*;
@ -79,7 +78,7 @@
//! static_locales!(LOCALES_SAMPLE); //! static_locales!(LOCALES_SAMPLE);
//! ``` //! ```
//! //!
//! Y si están en otro directorio, entonces puedes usar: //! But if they are in another directory, then you can use:
//! //!
//! ``` //! ```
//! use pagetop::prelude::*; //! use pagetop::prelude::*;
@ -114,10 +113,10 @@ static LANGUAGES: LazyStatic<HashMap<String, (LanguageIdentifier, &str)>> = Lazy
pub static LANGID_FALLBACK: LazyStatic<LanguageIdentifier> = LazyStatic::new(|| langid!("en-US")); pub static LANGID_FALLBACK: LazyStatic<LanguageIdentifier> = LazyStatic::new(|| langid!("en-US"));
/// Almacena el Identificador de Idioma Unicode /// Sets the application's default
/// ([Unicode Language Identifier](https://unicode.org/reports/tr35/tr35.html#Unicode_language_identifier)) /// [Unicode Language Identifier](https://unicode.org/reports/tr35/tr35.html#Unicode_language_identifier)
/// global para la aplicación a partir de `SETTINGS.app.language`. /// through `SETTINGS.app.language`.
pub static LANGID: LazyStatic<&LanguageIdentifier> = LazyStatic::new(|| { pub static LANGID_DEFAULT: LazyStatic<&LanguageIdentifier> = LazyStatic::new(|| {
langid_for(config::SETTINGS.app.language.as_str()).unwrap_or(&LANGID_FALLBACK) langid_for(config::SETTINGS.app.language.as_str()).unwrap_or(&LANGID_FALLBACK)
}); });
@ -130,10 +129,8 @@ pub fn langid_for(language: impl Into<String>) -> Result<&'static LanguageIdenti
Ok(&LANGID_FALLBACK) Ok(&LANGID_FALLBACK)
} else { } else {
Err(format!( Err(format!(
"{} Unicode Language Identifier \"{}\" is not accepted. {}", "Failed to get langid. Unicode Language Identifier \"{}\" is not accepted.",
"Failed to set language.", language,
config::SETTINGS.app.language,
"Using \"en-US\", check the settings file"
)) ))
} }
} }
@ -141,7 +138,7 @@ pub fn langid_for(language: impl Into<String>) -> Result<&'static LanguageIdenti
} }
#[macro_export] #[macro_export]
/// Define un conjunto de elementos de localización y textos locales de traducción. /// Defines a set of localization elements and local translation texts.
macro_rules! static_locales { macro_rules! static_locales {
( $LOCALES:ident $(, $core_locales:literal)? ) => { ( $LOCALES:ident $(, $core_locales:literal)? ) => {
$crate::locale::fluent_templates::static_loader! { $crate::locale::fluent_templates::static_loader! {
@ -149,8 +146,7 @@ macro_rules! static_locales {
locales: "src/locale", locales: "src/locale",
$( core_locales: $core_locales, )? $( core_locales: $core_locales, )?
fallback_language: "en-US", fallback_language: "en-US",
// Removes unicode isolating marks around arguments.
// Elimina las marcas Unicode que delimitan los argumentos.
customise: |bundle| bundle.set_use_isolating(false), customise: |bundle| bundle.set_use_isolating(false),
}; };
} }
@ -161,8 +157,7 @@ macro_rules! static_locales {
locales: $dir_locales, locales: $dir_locales,
$( core_locales: $core_locales, )? $( core_locales: $core_locales, )?
fallback_language: "en-US", fallback_language: "en-US",
// Removes unicode isolating marks around arguments.
// Elimina las marcas Unicode que delimitan los argumentos.
customise: |bundle| bundle.set_use_isolating(false), customise: |bundle| bundle.set_use_isolating(false),
}; };
} }
@ -253,7 +248,7 @@ impl ToString for L10n {
.lookup_with_args( .lookup_with_args(
match key.as_str() { match key.as_str() {
LANGUAGE_SET_FAILURE => &LANGID_FALLBACK, LANGUAGE_SET_FAILURE => &LANGID_FALLBACK,
_ => &LANGID, _ => &LANGID_DEFAULT,
}, },
key, key,
&self &self