Skip to main content

laravel_translatable/
lib.rs

1//! Translatable model attributes for Laravel Rust: a port of
2//! [spatie/laravel-translatable](https://github.com/spatie/laravel-translatable).
3//!
4//! Translations are stored as JSON, `{"en":"Hello","nl":"Hallo"}`, exactly as the PHP package
5//! stores them, so a database shared with a PHP application reads the same. See the
6//! [README](https://github.com/rivervo/laravel-translatable) for the guide.
7
8mod config;
9mod error;
10pub mod events;
11mod has_translations;
12mod provider;
13mod query;
14mod translations;
15
16pub use crate::config::{MissingKeyCallback, MissingTranslation, TranslatableConfig, locale, set_locale};
17pub use crate::error::AttributeIsNotTranslatable;
18pub use crate::has_translations::{AllTranslations, HasTranslations};
19pub use crate::provider::TranslatableServiceProvider;
20pub use crate::query::{
21    where_json_contains_locale, where_json_contains_locales, where_locale, where_locales, where_translation_like,
22};
23pub use crate::translations::{Translations, TranslationsField};
24
25/// Implements [`HasTranslations`] for a model, listing its translatable fields as PHP's
26/// `$translatable` property does. Each field is a [`Translations`] or an
27/// `Option<Translations>`:
28///
29/// ```ignore
30/// use laravel_translatable::{Translations, translatable};
31///
32/// #[model]
33/// pub struct NewsItem {
34///     pub id: i64,
35///     pub name: Translations,
36///     pub summary: Option<Translations>,
37/// }
38///
39/// translatable!(NewsItem { name, summary });
40/// ```
41#[macro_export]
42macro_rules! translatable {
43    ($model:ty { $($field:ident),+ $(,)? }) => {
44        impl $crate::HasTranslations for $model {
45            fn translatable_attributes() -> &'static [&'static str] {
46                &[$(stringify!($field)),+]
47            }
48
49            fn translations_field(&self, key: &str) -> ::core::option::Option<&dyn $crate::TranslationsField> {
50                match key {
51                    $(stringify!($field) => ::core::option::Option::Some(&self.$field),)+
52                    _ => ::core::option::Option::None,
53                }
54            }
55
56            fn translations_field_mut(
57                &mut self,
58                key: &str,
59            ) -> ::core::option::Option<&mut dyn $crate::TranslationsField> {
60                match key {
61                    $(stringify!($field) => ::core::option::Option::Some(&mut self.$field),)+
62                    _ => ::core::option::Option::None,
63                }
64            }
65        }
66    };
67}