Skip to content

Commit

Permalink
feat: Create mixin
Browse files Browse the repository at this point in the history
  • Loading branch information
LeadcodeDev committed Dec 11, 2022
1 parent c46631f commit 13fd8dd
Showing 1 changed file with 33 additions and 0 deletions.
33 changes: 33 additions & 0 deletions lib/src/mixins/translation.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import 'package:mineral_i18n/mineral_i18n.dart';
import 'package:mineral_ioc/ioc.dart';

mixin Translation {
I18n _getPlugin () {
final dynamic pluginManager = ioc.services.entries.firstWhere((element) => element.key.toString() == 'PluginManagerCraft').value;
return pluginManager.use<I18n>();
}

/// Translates the sentence defined by the key set into the requested language.
/// Replacement parameters can be injected.
/// ```dart
/// final String sentence = t(Lang.enGB, 'foo.bar');
/// print(sentence) 👈 'Hello {user}'
///
/// final String sentence = t(Lang.enGB, 'foo.bar', { 'user': 'Freeze' });
/// print(sentence) 👈 'Hello Freeze'
/// ```
String t (Lang lang, String key, { Map<String, dynamic>? replacers }) {
dynamic target = _getPlugin().translationManager.cache[lang.normalize];
for (final element in key.split('.')) {
target = target[element];
}

if (replacers != null) {
for (final replacer in replacers.entries) {
target = target.toString().replaceAll('{${replacer.key}}', replacer.value);
}
}

return target;
}
}

0 comments on commit 13fd8dd

Please sign in to comment.