-
-
Notifications
You must be signed in to change notification settings - Fork 218
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Askama base crate i18n support #845
Open
TTWNO
wants to merge
14
commits into
djc:main
Choose a base branch
from
TTWNO:askama_base_crate_i18n_support
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
14 commits
Select commit
Hold shift + click to select a range
2db3abe
Add fundementals for i18n in a new module
TTWNO cf707c9
Add i18n support to generator: visit_localize
TTWNO a0821b3
Add localizer to input
TTWNO 3ad39b4
Add localization expression type
TTWNO e70e93d
Cargo format
TTWNO 986ef3e
Add parsing tests for localization
TTWNO de9016c
Add i18n module
TTWNO e64226d
Add i18n featuree and optional dependencies
TTWNO ff92c60
Remove unsafe, unused code
TTWNO 4f1e5c7
Remove use of Unlazy
TTWNO 3d60dec
Add i18n module
TTWNO 889c51c
Add i18n featuree and optional dependencies
TTWNO 2f9a041
Remove unsafe, unused code
TTWNO 3630700
Merge branch 'askama_base_crate_i18n_support' of github.com:TTWNO/ask…
TTWNO File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,74 @@ | ||
//! Module for compile time checked localization | ||
//! | ||
//! # Example: | ||
//! | ||
//! [Fluent Translation List](https://projectfluent.org/) resource file `i18n/es-MX/basic.ftl`: | ||
//! | ||
//! ```ftl | ||
//! greeting = ¡Hola, { $name }! | ||
//! ``` | ||
//! | ||
//! Askama HTML template `templates/example.html`: | ||
//! | ||
//! ```html | ||
//! <h1>{{ localize("greeting", name: name) }}</h1> | ||
//! ``` | ||
//! | ||
//! Rust usage: | ||
//! ```ignore | ||
//! use askama::i18n::{langid, Locale}; | ||
//! use askama::Template; | ||
//! | ||
//! askama::i18n::load!(LOCALES); | ||
//! | ||
//! #[derive(Template)] | ||
//! #[template(path = "example.html")] | ||
//! struct ExampleTemplate<'a> { | ||
//! #[locale] | ||
//! loc: Locale<'a>, | ||
//! name: &'a str, | ||
//! } | ||
//! | ||
//! let template = ExampleTemplate { | ||
//! loc: Locale::new(langid!("es-MX"), &LOCALES), | ||
//! name: "Hilda", | ||
//! }; | ||
//! | ||
//! // "<h1>¡Hola, Hilda!</h1>" | ||
//! template.render().unwrap(); | ||
//! ``` | ||
|
||
use std::collections::HashMap; | ||
use std::iter::FromIterator; | ||
|
||
// Re-export conventiently as `askama::i18n::load!()`. | ||
// Proc-macro crates can only export macros from their root namespace. | ||
/// Load locales at compile time. See example above for usage. | ||
pub use askama_derive::i18n_load as load; | ||
|
||
pub use fluent_templates::{self, fluent_bundle::FluentValue, fs::langid, LanguageIdentifier}; | ||
use fluent_templates::{Loader, StaticLoader}; | ||
|
||
pub struct Locale<'a> { | ||
loader: &'a StaticLoader, | ||
language: LanguageIdentifier, | ||
} | ||
|
||
impl Locale<'_> { | ||
pub fn new(language: LanguageIdentifier, loader: &'static StaticLoader) -> Self { | ||
Self { loader, language } | ||
} | ||
|
||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Doc-comment here would be handy. |
||
pub fn translate<'a>( | ||
&self, | ||
msg_id: &str, | ||
args: impl IntoIterator<Item = (&'a str, FluentValue<'a>)>, | ||
) -> Option<String> { | ||
let args = HashMap::<&str, FluentValue<'_>>::from_iter(args); | ||
let args = match args.is_empty() { | ||
true => None, | ||
false => Some(&args), | ||
}; | ||
self.loader.lookup_complete(&self.language, msg_id, args) | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -66,6 +66,8 @@ | |
mod error; | ||
pub mod filters; | ||
pub mod helpers; | ||
#[cfg(feature = "i18n")] | ||
pub mod i18n; | ||
|
||
use std::fmt; | ||
|
||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -1376,9 +1376,40 @@ impl<'a> Generator<'a> { | |
Expr::RustMacro(ref path, args) => self.visit_rust_macro(buf, path, args), | ||
Expr::Try(ref expr) => self.visit_try(buf, expr.as_ref())?, | ||
Expr::Tuple(ref exprs) => self.visit_tuple(buf, exprs)?, | ||
Expr::Localize(ref msg_id, ref args) => self.visit_localize(buf, msg_id, args)?, | ||
}) | ||
} | ||
|
||
fn visit_localize( | ||
&mut self, | ||
buf: &mut Buffer, | ||
msg_id: &Expr<'_>, | ||
args: &[(&str, Expr<'_>)], | ||
) -> Result<DisplayWrap, CompileError> { | ||
let localizer = | ||
self.input.localizer.as_deref().ok_or( | ||
"You need to annotate a field with #[locale] to use the localize() function.", | ||
)?; | ||
|
||
buf.write(&format!( | ||
"self.{}.translate(", | ||
normalize_identifier(localizer) | ||
)); | ||
self.visit_expr(buf, msg_id)?; | ||
buf.writeln(", [")?; | ||
buf.indent(); | ||
for (k, v) in args { | ||
buf.write(&format!("({:?}, ::askama::i18n::FluentValue::from(", k)); | ||
self.visit_expr(buf, v)?; | ||
buf.writeln(")),")?; | ||
Comment on lines
+1401
to
+1404
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. personal preference for |
||
} | ||
buf.dedent()?; | ||
// Safe to unwrap, as `msg_id` is checked at compile time. | ||
buf.write("]).unwrap()"); | ||
|
||
Ok(DisplayWrap::Unwrapped) | ||
} | ||
|
||
fn visit_try( | ||
&mut self, | ||
buf: &mut Buffer, | ||
|
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
as this is a
fluid
backed i18n, would it be appropriate to self-document that in the feature name? e.g.i18n_fluent
?