### Run the example
Source: https://github.com/baptistemontan/leptos_i18n/blob/master/examples/dynamic_load/namespaces/README.md
Command to run the example using cargo_leptos.
```sh
cargo leptos watch
```
--------------------------------
### Build the example
Source: https://github.com/baptistemontan/leptos_i18n/blob/master/examples/dynamic_load/namespaces/README.md
Command to build the example using cargo_leptos.
```sh
cargo leptos build --release
```
--------------------------------
### Hydrate Configuration
Source: https://github.com/baptistemontan/leptos_i18n/blob/master/docs/book/src/02_getting_started.md
When compiling for the client, enable the `hydrate` feature.
```toml
# Cargo.toml
[features]
hydrate = [
"leptos_i18n/hydrate",
"leptos_i18n_build/hydrate",
]
```
--------------------------------
### Run the example
Source: https://github.com/baptistemontan/leptos_i18n/blob/master/examples/dynamic_load/axum_island/README.md
Command to run the example using cargo_leptos.
```sh
cargo leptos watch
```
--------------------------------
### Add leptos_i18n to your project using Cargo.toml
Source: https://github.com/baptistemontan/leptos_i18n/blob/master/docs/book/src/02_getting_started.md
Alternatively, add the crates to your Cargo.toml file.
```toml
[dependencies]
leptos_i18n = "0.6"
[build-dependencies]
leptos_i18n_build = "0.6"
```
--------------------------------
### Axum Backend Configuration
Source: https://github.com/baptistemontan/leptos_i18n/blob/master/docs/book/src/02_getting_started.md
When compiling for the backend using axum, enable the `axum` feature for the `leptos_i18n` crate.
```toml
# Cargo.toml
[features]
ssr = [
"leptos_i18n/axum",
"leptos_i18n_build/ssr",
]
```
--------------------------------
### Build the example
Source: https://github.com/baptistemontan/leptos_i18n/blob/master/examples/dynamic_load/axum_island/README.md
Command to build the example in release mode using cargo_leptos.
```sh
cargo leptos build --release
```
--------------------------------
### Client Side Rendering (CSR) Configuration
Source: https://github.com/baptistemontan/leptos_i18n/blob/master/docs/book/src/02_getting_started.md
When compiling for the client, enable the `csr` feature for both `leptos_i18n` and `leptos_i18n_build`.
```toml
# Cargo.toml
[dependencies.leptos_i18n]
features = ["csr"]
[build-dependencies.leptos_i18n_build]
features = ["csr"]
```
--------------------------------
### Actix-web Backend Configuration
Source: https://github.com/baptistemontan/leptos_i18n/blob/master/docs/book/src/02_getting_started.md
When compiling for the backend using actix-web, enable the `actix` feature for the `leptos_i18n` crate.
```toml
# Cargo.toml
[features]
ssr = [
"leptos_i18n/actix",
"leptos_i18n_build/ssr",
]
```
--------------------------------
### Add leptos_i18n to your project using cargo
Source: https://github.com/baptistemontan/leptos_i18n/blob/master/docs/book/src/02_getting_started.md
Add the leptos_i18n and leptos_i18n_build crates to your project's dependencies.
```bash
cargo add leptos_i18n leptos_i18n_build
```
--------------------------------
### Run the example
Source: https://github.com/baptistemontan/leptos_i18n/blob/master/examples/csr/interpolation/README.md
Command to run the interpolation example using trunk.
```bash
trunk serve --open
```
--------------------------------
### Install mdbook
Source: https://github.com/baptistemontan/leptos_i18n/blob/master/docs/book/README.md
Command to install the mdbook tool.
```bash
cargo install mdbook
```
--------------------------------
### Advanced ParseOptions example
Source: https://github.com/baptistemontan/leptos_i18n/blob/master/docs/book/src/setting_up/01_configuration.md
An example showcasing several advanced parsing options including file format, suppressing key warnings, enabling interpolate display, and showing keys only.
```rust
let options = ParseOptions::default()
.file_format(FileFormat::Json5)
.suppress_key_warnings(true)
.interpolate_display(true)
.show_keys_only(true);
```
--------------------------------
### Custom File Structure Example
Source: https://github.com/baptistemontan/leptos_i18n/blob/master/docs/book/src/setting_up/02_file_structure.md
An example of the file structure when a custom path is configured.
```bash
./path
└── to
└── mylocales
├── en.json
└── fr.json
```
--------------------------------
### Configuration with Namespaces
Source: https://github.com/baptistemontan/leptos_i18n/blob/master/docs/book/src/setting_up/03_namespaces.md
Example of how to add namespaces to the Leptos i18n configuration.
```rust
let cfg = Config::new("en")?.add_locale("fr")?.add_namespaces(["common", "home"]);
```
--------------------------------
### Currency formatter Rust example
Source: https://github.com/baptistemontan/leptos_i18n/blob/master/docs/book/src/declare/07_formatters.md
A Rust example for using the experimental currency formatter with a closure.
```rust
use crate::i18n::*;
let i18n = use_i18n();
let num = move || 100_000;
t!(i18n, currency_formatter, num);
```
--------------------------------
### Component Attributes Example
Source: https://github.com/baptistemontan/leptos_i18n/blob/master/docs/book/src/usage/04_t_macro.md
Example of passing attributes to components used in translations.
```rust
// key = "highlight me"
t!(i18n, key, id = "my_id", = , count = 0)
```
--------------------------------
### Build.rs Datagen Example
Source: https://github.com/baptistemontan/leptos_i18n/blob/master/docs/book/src/reduce_size/01_datagen.md
Example of a build.rs file for generating ICU4X data, including locales and plural markers.
```rust
use icu_provider_export::{
baked_exporter::{self, BakedExporter},
DataLocaleFamily,
DeduplicationStrategy,
ExportDriver,
ExportMetadata,
};
use std::path::PathBuf;
fn main() {
println!("cargo::rerun-if-changed=build.rs");
let mod_directory = PathBuf::from(std::env::var_os("OUT_DIR").unwrap()).join("baked_data");
let exporter = BakedExporter::new(mod_directory, {
let mut options = baked_exporter::Options::default();
options.overwrite = true;
options.use_internal_fallback = false;
options
})
.unwrap();
ExportDriver::new(
&[locale!("en"), locale!("fr")],
DeduplicationStrategy::None.into(),
LocaleFallbacker::new_without_data(),
)
.with_markers(&[icu::plurals::provider::MARKERS]);
}
```
--------------------------------
### List Formatter Usage Example
Source: https://github.com/baptistemontan/leptos_i18n/blob/master/docs/book/src/declare/07_formatters.md
Rust example demonstrating how to use the list formatter with a dynamic list variable.
```rust
use crate::i18n::*;
let i18n = use_i18n();
let list_var = move || ["A", "B", "C"];
t!(i18n, list_formatter, list_var);
```
--------------------------------
### Customizing parsing options with ParseOptions
Source: https://github.com/baptistemontan/leptos_i18n/blob/master/docs/book/src/setting_up/01_configuration.md
This example demonstrates how to customize parsing options, specifically setting the file format to YAML, within the build script configuration.
```rust
use leptos_i18n_build::{FileFormat, ParseOptions, TranslationsInfos};
use std::path::PathBuf;
use std::error::Error;
fn main() -> Result<(), Box> {
println!("cargo::rerun-if-changed=build.rs");
println!("cargo::rerun-if-changed=Cargo.toml");
let i18n_mod_directory = PathBuf::from(std::env::var_os("OUT_DIR").unwrap()).join("i18n");
let options = ParseOptions::default().file_format(FileFormat::Yaml);
let cfg = Config::new("en")?.add_locale("fr")?.parse_options(options);
let translations_infos = TranslationsInfos::parse(cfg)?;
translations_infos.emit_diagnostics();
translations_infos.rerun_if_locales_changed();
translations_infos.generate_i18n_module(i18n_mod_directory)?;
Ok(())
}
```
--------------------------------
### build.rs example for setting up translations
Source: https://github.com/baptistemontan/leptos_i18n/blob/master/docs/book/src/setting_up/01_configuration.md
This code snippet demonstrates how to use `leptos_i18n_build` in a `build.rs` file to generate translation code. It sets up default and additional locales, parses translation files, and emits necessary cargo commands.
```rust
use leptos_i18n_build::{TranslationsInfos, Config};
use std::path::PathBuf;
use std::error::Error;
fn main() -> Result<(), Box> {
println!("cargo::rerun-if-changed=build.rs");
println!("cargo::rerun-if-changed=Cargo.toml");
// where to generate the translations
let i18n_mod_directory = PathBuf::from(std::env::var_os("OUT_DIR").unwrap()).join("i18n");
let cfg = Config::new("en")?.add_locale("fr")?; // "en" is the default locale, "fr" is another locale.
let translations_infos = TranslationsInfos::parse(cfg)?;
// emit the errors and warnings found during parsing
translations_infos.emit_diagnostics();
// emit "cargo::rerun-if-changed" for every translation file
translations_infos.rerun_if_locales_changed();
// codegen
translations_infos.generate_i18n_module(i18n_mod_directory)?;
Ok(())
}
```
--------------------------------
### Codegen Options Example
Source: https://github.com/baptistemontan/leptos_i18n/blob/master/docs/book/src/setting_up/01_configuration.md
Demonstrates how to use `CodegenOptions` to customize the generated i18n module, including setting top-level attributes, customizing the file name, and enabling documentation generation.
```rust
use leptos_i18n_build::CodegenOptions;
let attributes = "#![allow(missing_docs)]".parse()?;
let options = CodegenOptions::default()
.top_level_attributes(Some(attributes))
.module_file_name("i18n.rs") // "mod.rs" by default
.gen_docs(true); // `true` by default
translations_infos.generate_i18n_module_with_options(options)?;
```
--------------------------------
### Number formatter Rust example
Source: https://github.com/baptistemontan/leptos_i18n/blob/master/docs/book/src/declare/07_formatters.md
A Rust example demonstrating how to use the number formatter with a closure.
```rust
use crate::i18n::*;
let i18n = use_i18n();
let num = move || 100_000;
t!(i18n, number_formatter, num);
```
--------------------------------
### Configuring locales with Config builder
Source: https://github.com/baptistemontan/leptos_i18n/blob/master/docs/book/src/setting_up/01_configuration.md
Example of using the `Config` builder to declare 'en' and 'fr' as supported locales, with 'en' as the default.
```rust
let cfg = Config::new("en")?.add_locale("fr")?;
```
--------------------------------
### Time Formatter Rust Example
Source: https://github.com/baptistemontan/leptos_i18n/blob/master/docs/book/src/declare/07_formatters.md
Rust code example demonstrating the usage of the time formatter with a variable.
```rust
use crate::i18n::*;
use leptos_i18n::reexports::icu::datetime::input::Time;
let i18n = use_i18n();
let time_var = move || Time::try_new(14, 34, 28, 0).unwrap();
t!(i18n, time_formatter, time_var);
```
--------------------------------
### Custom Formatter Implementation
Source: https://github.com/baptistemontan/leptos_i18n/blob/master/docs/book/src/appendix_custom_formatter.md
An example of implementing a custom formatter for left or right padding.
```rust
impl PadFormatter {
fn view_bounds(&self) -> TokenStream {
quote!(core::fmt::Display)
}
fn to_view(&self, key: &syn::Ident, locale_field: &syn::Ident) -> TokenStream {
// the locale is irrelevant here, we can ignore it.
let _ = locale_field;
let fmt_string = match self.direction {
PadDirection::Left => {
format!("{{:<{}}}", self.total_len)
}
PadDirection::Right => {
format!("{{:>{}}}", self.total_len)
}
};
// In the codegen for the to into_view implementation,
// it is expected to return something that implement `IntoView` and is 'static
quote! {
std::format!(#fmt_string, #key)
}
}
}
```
--------------------------------
### DateTime Formatter Rust Example
Source: https://github.com/baptistemontan/leptos_i18n/blob/master/docs/book/src/declare/07_formatters.md
Rust code example demonstrating the usage of the datetime formatter with a variable.
```rust
use crate::i18n::*;
use leptos_i18n::reexports::icu::datetime::input::{Date, DateTime, Time};
let i18n = use_i18n();
let datetime_var = move || {
let date = Date::try_new_iso(1970, 1, 2).unwrap().to_any();
let time = Time::try_new(14, 34, 28, 0).unwrap();
DateTime::new(date, time)
};
t!(i18n, datetime_formatter, datetime_var);
```
--------------------------------
### Time Formatter Example
Source: https://github.com/baptistemontan/leptos_i18n/blob/master/docs/book/src/declare/07_formatters.md
Example of how to define a time formatter in JSON.
```json
{
"time_formatter": "{{ time_var, time }}"
}
```
--------------------------------
### build.rs example for data generation
Source: https://github.com/baptistemontan/leptos_i18n/blob/master/docs/book/src/reduce_size/01_datagen.md
A basic build script demonstrating how to use leptos_i18n_build to parse configurations and translations, and generate data.
```rust
use leptos_i18n_build::{TranslationsInfos, Config};
use std::path::PathBuf;
fn main() {
println!("cargo::rerun-if-changed=build.rs");
println!("cargo::rerun-if-changed=Cargo.toml");
let mod_directory = PathBuf::from(std::env::var_os("OUT_DIR").unwrap()).join("baked_data");
let cfg: Config = // ...;
let translations_infos = TranslationsInfos::parse(cfg).unwrap();
translations_infos.rerun_if_locales_changed();
translations_infos.generate_data(mod_directory).unwrap();
}
```
--------------------------------
### Date Formatter Rust Example
Source: https://github.com/baptistemontan/leptos_i18n/blob/master/docs/book/src/declare/07_formatters.md
Rust code example demonstrating the usage of the date formatter with a variable.
```rust
use crate::i18n::*;
use leptos_i18n::reexports::icu::datetime::input::Date;
let i18n = use_i18n();
let date_var = move || Date::try_new_iso(1970, 1, 2).unwrap().to_any();
t!(i18n, date_formatter, date_var);
```
--------------------------------
### DateTime Formatter Example
Source: https://github.com/baptistemontan/leptos_i18n/blob/master/docs/book/src/declare/07_formatters.md
Example of how to define a datetime formatter in JSON.
```json
{
"datetime_formatter": "{{ datetime_var, datetime }}"
}
```
--------------------------------
### `td_format_string!` example with date formatting
Source: https://github.com/baptistemontan/leptos_i18n/blob/master/docs/book/src/usage/09_t_format.md
Shows how to use `td_format_string!` for date formatting with different locale options.
```rust
let date = move || Date::try_new_iso(1970, 1, 2).unwrap().to_any();
let en = td_format_string!(Locale::en, date, formatter: date);
assert_eq!(en, "Jan 2, 1970");
let fr = td_format_string!(Locale::fr, date, formatter: date(date_length: long));
assert_eq!(fr, "2 janvier 1970");
```
--------------------------------
### Adding a Custom Formatter
Source: https://github.com/baptistemontan/leptos_i18n/blob/master/docs/book/src/appendix_custom_formatter.md
Example of how to add a custom formatter to the parsing options in `build.rs`.
```rust
let options = ParseOptions::new().add_formatter(PaddingFormatterParser);
let cfg = cfg.parse_options(options);
let translations_infos = TranslationsInfos::parse(cfg).unwrap();
```
--------------------------------
### Load Custom Data Provider
Source: https://github.com/baptistemontan/leptos_i18n/blob/master/docs/book/src/reduce_size/01_datagen.md
Example of how to load a custom data provider in Rust.
```rust
include!(concat!(env!("OUT_DIR"), "/baked_data/mod.rs"));
pub struct MyDataProvider;
impl_data_provider!(MyDataProvider);
```
--------------------------------
### Including alloc crate and implementing data provider
Source: https://github.com/baptistemontan/leptos_i18n/blob/master/docs/book/src/reduce_size/01_datagen.md
Example of how to include the 'alloc' crate and implement a custom data provider macro for experimental features.
```rust
extern crate alloc;
include!(concat!(env!("OUT_DIR"), "/baked_data/mod.rs"));
pub struct MyDataProvider;
impl_data_provider!(MyDataProvider);
```
--------------------------------
### Currency formatter example
Source: https://github.com/baptistemontan/leptos_i18n/blob/master/docs/book/src/declare/07_formatters.md
Shows the JSON key for using the experimental currency formatter.
```json
{
"currency_formatter": "{{ num, currency }}"
}
```
--------------------------------
### Full Time Formatter Example
Source: https://github.com/baptistemontan/leptos_i18n/blob/master/docs/book/src/declare/07_formatters.md
Example of how to define a full time formatter in JSON.
```json
{
"full_time_formatter": "{{ time_var, time(length: long) }}"
}
```
--------------------------------
### Short Date Formatter Example
Source: https://github.com/baptistemontan/leptos_i18n/blob/master/docs/book/src/declare/07_formatters.md
Example of how to define a short date formatter in JSON.
```json
{
"short_date_formatter": "{{ date_var, date(length: short) }}"
}
```
--------------------------------
### Basic I18nRoute Usage
Source: https://github.com/baptistemontan/leptos_i18n/blob/master/docs/book/src/usage/07_router.md
Example demonstrating how to use the I18nRoute component within a Leptos router to manage locale-based routing.
```rust
use crate::i18n::Locale;
use leptos_i18n_router::I18nRoute;
use leptos::prelude::*;
use leptos_router::*;
view! {
view=Outlet>
>
}
```
--------------------------------
### Island Example
Source: https://github.com/baptistemontan/leptos_i18n/blob/master/docs/book/src/usage/02_context.md
If you use the `islands` feature from Leptos, the `I18nContextProvider` loses two props: `cookie_options` and `ssr_lang_header_getter`, because they are not serializable. If you need them, you can use the `init_context_with_options` function and provide the context yourself:
```rust
use leptos_i18n::init_i18n_context_with_options;
use leptos_i18n::context::{CookieOptions, UseLocalesOptions};
use leptos_meta::Html;
use leptos::prelude::*;
use crate::i18n::*;
#[island]
fn MyI18nProvider(
enable_cookie: Option,
cookie_name: Option<&str>,
children: Children
) -> impl IntoView {
let my_cookie_options: CookieOptions = /* create your options here */;
let ssr_lang_header_getter: UseLocalesOptions = /* create your options here */;
let i18n = init_i18n_context_with_options::(
enable_cookie,
cookie_name,
Some(my_cookie_options),
Some(ssr_lang_header_getter)
);
provide_context(i18n);
let lang = move || i18n.get_locale().as_str();
let dir = move || i18n.get_locale().direction().as_str();
view! {
{children}
}
}
```
--------------------------------
### JSON Configuration for Custom Formatter
Source: https://github.com/baptistemontan/leptos_i18n/blob/master/docs/book/src/appendix_custom_formatter.md
Example of how to use the custom padding formatter in a JSON localization file.
```json
{
"custom_formatter": "{{ var, padding(len: 14) }}",
"right_padded": "{{ var, padding(len: 23; dir: right) }}"
}
```
--------------------------------
### Conditional Logic Example (Not Recommended)
Source: https://github.com/baptistemontan/leptos_i18n/blob/master/docs/book/src/declare/03_plurals.md
Illustrates a manual approach to pluralization that is not recommended due to language variations.
```rust,ignore
if item_count == 1 {
t!(i18n, items_one)
} else {
t!(i18n, items_other, count = move || item_count)
}
```
--------------------------------
### Date formatter example
Source: https://github.com/baptistemontan/leptos_i18n/blob/master/docs/book/src/declare/07_formatters.md
Illustrates the JSON key for using the date formatter.
```json
{
"date_formatter": "{{ date_var, date }}"
}
```
--------------------------------
### Accessing subkeys in Rust
Source: https://github.com/baptistemontan/leptos_i18n/blob/master/docs/book/src/declare/04_subkeys.md
These Rust examples demonstrate how to access the declared subkeys using the t! macro.
```rust
t!(i18n, subkeys.subkey_1);
// -> "This is subkey_1"
t!(i18n, subkeys.nested_subkeys.nested_subkey_1);
// -> "you can nest subkeys"
```
--------------------------------
### Setting lang attribute manually
Source: https://github.com/baptistemontan/leptos_i18n/blob/master/docs/book/src/usage/02_context.md
An example of manually setting the 'lang' attribute on an HTML element.
```html
```
--------------------------------
### Basic Interpolation Example
Source: https://github.com/baptistemontan/leptos_i18n/blob/master/docs/book/src/usage/06_td_string_macro.md
Demonstrates using `td_string!` for simple interpolations with numbers and strings.
```rust
// click_count = "You clicked {{ count }} times"
assert_eq!(
td_string!(Locale::en, click_count, count = 10),
"You clicked 10 times"
)
assert_eq!(
td_string!(Locale::en, click_count, count = "a lot of"),
"You clicked a lot of times"
)
```
--------------------------------
### Registering Server Functions
Source: https://github.com/baptistemontan/leptos_i18n/blob/master/docs/book/src/reduce_size/02_dynamic_load.md
Example of how to manually register server functions for dynamic translation loading when using a backend that requires explicit registration.
```rust
use i18n::Locale;
use leptos_i18n::Locale as LocaleTrait;
register_server_fn::<::ServerFn>();
```
--------------------------------
### `td_display!` Macro Example
Source: https://github.com/baptistemontan/leptos_i18n/blob/master/docs/book/src/usage/06_td_string_macro.md
Demonstrates the usage of the `td_display!` macro, which returns a struct implementing `Display`.
```rust
use crate::i18n::Locale;
use leptos_i18n::td_display;
// click_count = "You clicked {{ count }} times"
let t = td_display!(Locale::en, click_count, count = 10); // this only returns the builder, no work has been done.
assert_eq!(format!("before {t} after"), "before You clicked 10 times after");
let t_str = t.to_string(); // can call `to_string` as the value implements `Display`
assert_eq!(t_str, "You clicked 10 times");
```
--------------------------------
### Set Custom Provider for SSR Apps (Server Startup)
Source: https://github.com/baptistemontan/leptos_i18n/blob/master/docs/book/src/reduce_size/01_datagen.md
Setting the custom data provider during server startup for Server-Side Rendered (SSR) Leptos applications, shown with an Actix example.
```rust
// example for actix
#[actix_web::main]
async fn main() -> std::io::Result<()> {
leptos_i18n::custom_provider::set_icu_data_provider(MyDataProvider);
// ..
}
```
--------------------------------
### Attempted Reactive Usage (Fails)
Source: https://github.com/baptistemontan/leptos_i18n/blob/master/docs/book/src/appendix_custom_formatter.md
An example showing an attempt to use a reactive value with the custom formatter, which results in a compile-time error.
```rust
let i18n = use_i18n();
let value = Signal::new(14);
t!(i18n, custom_formatter, var = || value.get())
```
--------------------------------
### Basic Key-Value Pair
Source: https://github.com/baptistemontan/leptos_i18n/blob/master/docs/book/src/declare/01_key_value.md
A simple example of a translation declared as a key-value pair in JSON format.
```json
{
"hello_world": "Hello World!"
}
```
--------------------------------
### Layout with potential locale mismatch
Source: https://github.com/baptistemontan/leptos_i18n/blob/master/docs/book/src/usage/07_router.md
This layout shows a common setup where the Menu component might experience a locale mismatch with the router.
```rust
view! {
view=Outlet>
>
}
```
--------------------------------
### JSON structure for subkeys
Source: https://github.com/baptistemontan/leptos_i18n/blob/master/docs/book/src/declare/04_subkeys.md
This JSON example shows how to define nested subkeys and even HTML within a translation string.
```json
{
"subkeys": {
"subkey_1": "This is subkey_1",
"subkey_n": "This is subkey {{ n }}",
"nested_subkeys": {
"nested_subkey_1": "you can nest subkeys"
}
}
}
```
--------------------------------
### Initializing a Sub-context with a custom locale signal
Source: https://github.com/baptistemontan/leptos_i18n/blob/master/docs/book/src/usage/03_subcontext.md
Example demonstrating how to initialize a sub-context where the locale is derived from the parent context's locale, specifically negating it (e.g., English becomes French and vice-versa).
```rust
fn neg_locale(locale: Locale) -> Locale {
match locale {
Locale::en => Locale::fr,
Locale::fr => Locale::en
}
}
fn neg_i18n_signal(i18n: I18nContext) -> Signal {
Signal::derive(move || neg_locale(i18n.get()))
}
fn opposite_context() {
let i18n = use_i18n();
let ctx = init_i18n_subcontext(Some(neg_i18n_signal(i18n)));
// ..
}
```
--------------------------------
### Custom Component Rendering Function
Source: https://github.com/baptistemontan/leptos_i18n/blob/master/docs/book/src/usage/06_td_string_macro.md
Provides an example of a custom function for rendering components with finer control over formatting, including attributes and children.
```rust
use core::fmt::{Formatter, Result};
use leptos_i18n::display::{Attributes, Children};
fn render_b(f: &mut Formatter, child: Children, attrs: Attributes) -> Result {
write!(f, "
{child}
")
}
// hello_world = "Hello World !"
let hw = td_string!(Locale::en, hello_world, foo = "bar", = render_b);
assert_eq!(hw, "Hello
World
!");
```
--------------------------------
### Example Inheritance Tree
Source: https://github.com/baptistemontan/leptos_i18n/blob/master/docs/book/src/setting_up/04_inheritance.md
This tree illustrates the automatic inheritance relationships between locales based on their naming conventions. More specific locales inherit from more general ones.
```text
en (default)
├── en-US
│ ├── en-Latn-US-Valencia
│ ├── en-Latn-US-Valencia-u-ca-buddhist
│ └── en-Latn-US-u-ca-buddhist
├── en-Valencia
├── en-Latn
└── fr
├── fr-FR
│ └── fr-FR-u-ca-buddhist
└── fr-u-ca-buddhist
```
--------------------------------
### Basic usage of t_plural!
Source: https://github.com/baptistemontan/leptos_i18n/blob/master/docs/book/src/usage/10_t_plural.md
Demonstrates how to use the `t_plural!` macro to select a translation based on a count, with examples for 'one' and a fallback 'other'. It also shows how to use the result within an effect.
```rust
let i18n = use_i18n();
let form = t_plural! {
i18n,
count = || 0,
one => "one",
_ => "other"
};
Effect::new(|| {
let s = form();
log!("{}", s);
})
```
--------------------------------
### Argument Types for Foreign Keys
Source: https://github.com/baptistemontan/leptos_i18n/blob/master/docs/book/src/declare/05_foreign_keys.md
Provides examples of different argument types (string, boolean, number, interpolated, foreign key) that can be supplied to foreign keys.
```json
{
"key": "{{ arg }}",
"string_arg": "$t(key, {\"arg\": \"str\"})",
"boolean_arg": "$t(key, {\"arg\": true})",
"number_arg": "$t(key, {\"arg\": 56})",
"interpolated_arg": "$t(key, {\"arg\": \"value: {{ new_arg }}\"})",
"foreign_key_arg": "$t(key, {\"arg\": \"value: $t(interpolated_arg)\"})"
}
```
--------------------------------
### Basic Usage of Custom Formatter
Source: https://github.com/baptistemontan/leptos_i18n/blob/master/docs/book/src/appendix_custom_formatter.md
Demonstrates how to use the custom formatter with a static value.
```rust
let i18n = use_i18n();
t_string!(i18n, custom_formatter, var = 14)
```
--------------------------------
### Basic `t_format!` usage
Source: https://github.com/baptistemontan/leptos_i18n/blob/master/docs/book/src/usage/09_t_format.md
Demonstrates how to use the `t_format!` macro with a number formatter.
```rust
use crate::i18n::*;
use leptos_i18n::formatting::t_format;
let i18n = use_i18n();
let num = move || 100_000;
t_format!(i18n, num, formatter: number);
```
--------------------------------
### Correctly shadowing a context using Provider
Source: https://github.com/baptistemontan/leptos_i18n/blob/master/docs/book/src/usage/03_subcontext.md
Demonstrates the recommended approach for shadowing contexts by using a `leptos::Provider` to wrap the sub-context, ensuring isolation.
```rust
@component
fn Sub() -> impl IntoView {
let i18n = init_i18n_subcontext();
view! {
{t!(i18n, sub)}
}
}
```
--------------------------------
### Including the generated i18n module
Source: https://github.com/baptistemontan/leptos_i18n/blob/master/docs/book/src/setting_up/01_configuration.md
This snippet shows how to include the translation module generated by the build script into your Rust project.
```rust
include!(concat!(env!("OUT_DIR"), "/i18n/mod.rs"));
use i18n::*;
```
--------------------------------
### Short Date Long Time Formatter Example
Source: https://github.com/baptistemontan/leptos_i18n/blob/master/docs/book/src/declare/07_formatters.md
Example of how to define a datetime formatter with specific length and time precision in JSON.
```json
{
"short_date_long_time_formatter": "{{ datetime_var, datetime(length: short; time_precision: minute) }}"
}
```
--------------------------------
### Interpolate Values
Source: https://github.com/baptistemontan/leptos_i18n/blob/master/docs/book/src/declare/02_interpolation.md
Example of declaring a translation with an interpolated value.
```json
{
"click_count": "You clicked {{ count }} times"
}
```
--------------------------------
### Component Attributes
Source: https://github.com/baptistemontan/leptos_i18n/blob/master/docs/book/src/declare/02_interpolation.md
Example of declaring a translation with a component that has an HTML attribute.
```json
{
"highlight_me": "highlight me"
}
```
--------------------------------
### Component Attributes with Variables
Source: https://github.com/baptistemontan/leptos_i18n/blob/master/docs/book/src/declare/02_interpolation.md
Example of using variables within component attributes.
```json
{
"with_break": "some line some other line"
}
```
--------------------------------
### Interpolate Components (Self-closing)
Source: https://github.com/baptistemontan/leptos_i18n/blob/master/docs/book/src/declare/02_interpolation.md
Example of declaring a translation with a self-closing interpolated component.
```json
{
"with_break": "some line some other line"
}
```
--------------------------------
### Using the generated I18nSubContextProvider
Source: https://github.com/baptistemontan/leptos_i18n/blob/master/docs/book/src/usage/03_subcontext.md
Shows the usage of the `I18nSubContextProvider` generated by the `leptos_i18n` macro, which correctly handles sub-context provision.
```rust
use crate::i18n::*;
use leptos::prelude::*;
#[component]
fn Foo() -> impl IntoView {
view! {
}
}
#[component]
fn Sub() -> impl IntoView {
let i18n = use_i18n();
view! {
{t!(i18n, sub)}
}
}
```
--------------------------------
### Number formatter example
Source: https://github.com/baptistemontan/leptos_i18n/blob/master/docs/book/src/declare/07_formatters.md
Illustrates the JSON key for using the number formatter.
```json
{
"number_formatter": "{{ num, number }}"
}
```
--------------------------------
### Basic Plural Definition
Source: https://github.com/baptistemontan/leptos_i18n/blob/master/docs/book/src/declare/03_plurals.md
Example of defining plural forms for a key in JSON.
```json
{
"items_one": "{{ count }} item",
"items_other": "{{ count }} items"
}
```
--------------------------------
### Plurals with `t!` macro
Source: https://github.com/baptistemontan/leptos_i18n/blob/master/docs/book/src/usage/04_t_macro.md
Example of using the `t!` macro to handle pluralization, expecting a `count` variable.
```rust
t!(i18n, key_to_plurals, count = count);
```
--------------------------------
### Disabling a Formatter
Source: https://github.com/baptistemontan/leptos_i18n/blob/master/docs/book/src/appendix_custom_formatter.md
Example of how to disable a formatter by setting the `DISABLED` constant in the `Formatter` trait.
```rust
impl FormatterToTokens for PaddingFormatter {
const DISABLED: Option<&str> = const {
if SOME_CONDITIONS {
None
} else {
Some("padding formatter is disabled")
}
};
// ...
}
```
--------------------------------
### Using I18nContext as a Leptos Directive
Source: https://github.com/baptistemontan/leptos_i18n/blob/master/docs/book/src/usage/02_context.md
Demonstrates how to use the I18nContext directive to automatically set 'lang' and 'dir' attributes on an element.
```rust
let i18n = use_i18n();
view! {
}
```
--------------------------------
### Using `scope_i18n!` Macro
Source: https://github.com/baptistemontan/leptos_i18n/blob/master/docs/book/src/usage/08_scoping.md
Demonstrates how to use the `scope_i18n!` macro to shorten repetitive key access within a namespace.
```rust
let i18n = use_i18n();
t!(i18n, namespace.subkeys.value);
t!(i18n, namespace.subkeys.more_subkeys.subvalue);
t!(i18n, namespace.subkeys.more_subkeys.another_subvalue);
```
```rust
let i18n = use_i18n();
let i18n = scope_i18n!(i18n, namespace.subkeys);
t!(i18n, value);
t!(i18n, more_subkeys.subvalue);
t!(i18n, more_subkeys.another_subvalue);
```
--------------------------------
### Localized Path Segments with i18n_path! Macro
Source: https://github.com/baptistemontan/leptos_i18n/blob/master/docs/book/src/usage/07_router.md
Demonstrates using the i18n_path! macro within I18nRoute to create dynamic, localized path segments.
```rust
use leptos_i18n_router::i18n_path;
view=Outlet>
>
```
--------------------------------
### Ordinal Plural Definition
Source: https://github.com/baptistemontan/leptos_i18n/blob/master/docs/book/src/declare/03_plurals.md
Example of defining ordinal plural forms for a key in JSON.
```json
{
"key_ordinal_one": "{{ count }}st place",
"key_ordinal_two": "{{ count }}nd place",
"key_ordinal_few": "{{ count }}rd place",
"key_ordinal_other": "{{ count }}th place"
}
```
--------------------------------
### Using `DisplayComp` for Attributes
Source: https://github.com/baptistemontan/leptos_i18n/blob/master/docs/book/src/usage/06_td_string_macro.md
Illustrates how to use the `DisplayComp` struct to pass attributes to interpolated components.
```rust
let attrs = [("id", "my_id")];
let b = DisplayComp::new("div", &attrs);
let hw = td_string!(Locale::en, hello_world, );
assert_eq!(hw, "Hello
World
!");
```
--------------------------------
### Use Both Interpolated Values and Components
Source: https://github.com/baptistemontan/leptos_i18n/blob/master/docs/book/src/declare/02_interpolation.md
Example of a translation that combines interpolated values and components.
```json
{
"click_count": "You clicked {{ count }} times"
}
```
--------------------------------
### Interpolate Components (HTML)
Source: https://github.com/baptistemontan/leptos_i18n/blob/master/docs/book/src/declare/02_interpolation.md
Example of declaring a translation with an interpolated component using HTML tags.
```json
{
"highlight_me": "highlight me"
}
```
--------------------------------
### Using `define_scope!` Macro
Source: https://github.com/baptistemontan/leptos_i18n/blob/master/docs/book/src/usage/08_scoping.md
Shows how `define_scope!` creates a marker type for reusable scope definitions.
```rust
type SubkeysScope = define_scope!(crate::i18n, namespace.subkeys);
fn foo(locale: Locale) {
let locale = locale.scope::();
td!(locale, value);
let locale = scope_locale!(locale, more_subkeys);
td!(locale, subvalue);
td!(locale, another_subvalue);
}
fn bar() -> impl IntoView {
let i18n = use_i18n_scoped::();
// equivalent to `use_i18n().scope::()`
t!(i18n, value)
}
```
--------------------------------
### Trunk Configuration for Copying Translation Files
Source: https://github.com/baptistemontan/leptos_i18n/blob/master/docs/book/src/reduce_size/02_dynamic_load.md
HTML snippet for `index.html` to instruct Trunk to copy the generated translation JSON files into the build output directory.
```html
```
--------------------------------
### Combining options for data generation
Source: https://github.com/baptistemontan/leptos_i18n/blob/master/docs/book/src/reduce_size/01_datagen.md
Illustrates how to combine different options, like plurals and formatters, by merging their data markers.
```rust
use leptos_i18n_build::Options;
let mut markers = &[icu::plurals::provider::MARKERS];
let markers.extend(Options::FormatDateTime.into_data_markers());
// markers now contains the `DataMarker`s needed for plurals and for the `time`, `date` and `datetime` formatters.
translations_infos.generate_data_with_data_markers(mod_directory, markers).unwrap();
```
--------------------------------
### Change the Locale
Source: https://github.com/baptistemontan/leptos_i18n/blob/master/docs/book/src/usage/02_context.md
With the context, you can change the current locale with the `set_locale` method. For example, this component will switch between `en` and `fr` with a button:
```rust
use crate::i18n::*;
use leptos::prelude::*;
#[component]
pub fn Foo() -> impl IntoView {
let i18n = use_i18n();
let on_switch = move |_| {
let new_locale = match i18n.get_locale() {
Locale::en => Locale::fr,
Locale::fr => Locale::en,
};
i18n.set_locale(new_locale);
};
view! {
}
}
```
--------------------------------
### Foreign Keys with Namespaces and Subkeys
Source: https://github.com/baptistemontan/leptos_i18n/blob/master/docs/book/src/declare/05_foreign_keys.md
Illustrates how to reference keys within namespaces and subkeys using dot notation.
```json
$t(namespace:key.subkey.subsubkey)
```
--------------------------------
### Basic `td!` Macro Usage
Source: https://github.com/baptistemontan/leptos_i18n/blob/master/docs/book/src/usage/05_td_macro.md
Demonstrates the basic syntax of the `td!` macro, taking a locale and a translation key as arguments.
```rust
td!(Locale::fr, hello_world)
```
--------------------------------
### Add leptos_i18n to your project
Source: https://github.com/baptistemontan/leptos_i18n/blob/master/README.md
You can add the crate to your project with
```bash
cargo add leptos_i18n
```
--------------------------------
### Example of Explicit Inheritance
Source: https://github.com/baptistemontan/leptos_i18n/blob/master/docs/book/src/setting_up/04_inheritance.md
This Rust code demonstrates how to make a specific locale inherit from another, overriding the default automatic inheritance.
```rust
let cfg = cfg.extend_locale("en-Latn-US-Valencia-u-ca-buddhist", "en-Latn-US-Valencia")?;
```
--------------------------------
### Namespace access with `::` separator
Source: https://github.com/baptistemontan/leptos_i18n/blob/master/docs/book/src/usage/04_t_macro.md
Alternative syntax for accessing namespaces using `::` to separate the namespace from the key.
```rust
t!(i18n, my_namespace::hello_world)
```
--------------------------------
### Using `scope_locale!` Macro
Source: https://github.com/baptistemontan/leptos_i18n/blob/master/docs/book/src/usage/08_scoping.md
Demonstrates scoping a `Locale` context using `scope_locale!` for repetitive `td!` calls.
```rust
fn foo(locale: Locale) {
td!(locale, namespace.subkeys.value);
td!(locale, namespace.subkeys.more_subkeys.subvalue);
td!(locale, namespace.subkeys.more_subkeys.another_subvalue);
}
```
```rust
fn foo(locale: Locale) {
let locale = scope_locale!(locale, namespace.subkeys);
td!(locale, value);
td!(locale, more_subkeys.subvalue);
td!(locale, more_subkeys.another_subvalue);
}
```
--------------------------------
### Accessing Locale in Server Functions
Source: https://github.com/baptistemontan/leptos_i18n/blob/master/docs/book/src/usage/12_serverfn.md
Example of how to resolve the user's locale within a Leptos server function using `leptos_i18n::locale::resolve_locale()`.
```rust
#[server]
async fn get_locale() -> Result {
let locale: Locale = leptos_i18n::locale::resolve_locale();
Ok(locale)
}
```
--------------------------------
### Modified Inheritance Tree after Explicit Configuration
Source: https://github.com/baptistemontan/leptos_i18n/blob/master/docs/book/src/setting_up/04_inheritance.md
This tree shows the updated inheritance structure after applying the explicit inheritance rule from the previous example.
```text
en (default)
├── en-US
│ ├── en-Latn-US-Valencia
│ │ └── en-Latn-US-Valencia-u-ca-buddhist
│ └── en-Latn-US-u-ca-buddhist
├── en-Valencia
├── en-Latn
└── fr
├── fr-FR
│ └── fr-FR-u-ca-buddhist
└── fr-u-ca-buddhist
```
--------------------------------
### Component Closure Syntax for Attributes
Source: https://github.com/baptistemontan/leptos_i18n/blob/master/docs/book/src/usage/04_t_macro.md
Demonstrates how to use closure syntax to pass attributes to components within translations.
```rust
use leptos::children::ChildrenFn;
use leptos::attr::any_attribute::AnyAttribute;
let b = |children: ChildrenFn, attr: Vec| view!{ {children} }
t!(i18n, highlight_me, id = "my_id", )
```
--------------------------------
### Explicitly Using Default Locale Value
Source: https://github.com/baptistemontan/leptos_i18n/blob/master/docs/book/src/declare/01_key_value.md
Demonstrates how to explicitly indicate that a value should use the default locale's value by setting it to null, preventing warnings.
```json
{
"take_value_of_default": null
}
```
--------------------------------
### Generating data with additional options
Source: https://github.com/baptistemontan/leptos_i18n/blob/master/docs/book/src/reduce_size/01_datagen.md
Demonstrates how to provide additional options, such as formatters, to the data generation process.
```rust
use leptos_i18n_build::Options;
translations_infos.generate_data_with_options(mod_directory, [Options::FormatDateTime]).unwrap();
```