Laratext Rust

Laratext Rust names a string with a stable key and a readable default in the same call, then fills in the other languages for you from a scan of your source. It works in Rust, in MiniJinja views and in the JavaScript of React, Vue, Svelte and Alpine.
Written against version 0.1, which targets Laravel Rust 0.1 (in beta). Its API follows the framework's changes until 1.0.
This is the port of Laratext, the PHP package, and its behaviour and names follow it. The crate is on crates.io and its API reference is on docs.rs. It reads the current locale from Laralocale for Laravel Rust, which has to be registered as well. For a step-by-step tutorial in Spanish, see Cómo traducir textos en Laravel Rust con Laratext on Neoguias.
Installation
cargo add laratext laralocale
Laralocale does not choose the language of a request by itself: add a middleware that calls laralocale::set_locale(request.preferred_locale()), as its documentation shows, or use LaralocaleServiceProvider::new().with_detection() to detect it from the query string, the session, a cookie or the browser. Register both service providers in src/app.rs, and list the locales you support:
use laralocale::{LaralocaleServiceProvider, LocaleConfig}; use laratext::{LaratextServiceProvider, TextsConfig}; use laravel::Application; pub fn configure() -> ApplicationBuilder { Application::configure() .with_providers(|providers| { providers.add(LaralocaleServiceProvider::new()); providers.add(LaratextServiceProvider::new()); }) .with_config(|config, _| { config.section_mut::<LocaleConfig>().supported = ["en", "es", "fr"].map(str::to_owned).to_vec(); let texts = config.section_mut::<TextsConfig>(); texts.languages = [("en", "English"), ("es", "Spanish"), ("fr", "French")] .into_iter() .map(|(code, name)| (code.to_owned(), name.to_owned())) .collect(); }) }
The provider adds the configuration, the commands, the translators, the text() and texts() functions in the views and the JavaScript module under /vendor/laratext/. The translations live in lang/{locale}.json, in the base path of the application, as in Laravel. Laravel Rust has no lang_path(), so TextsConfig::lang_path (lang by default) names the folder.
Naming a string
The core is one function. You give it a key and the readable text as a default, and it returns the translation for the current locale, falling back to your default when there is not one yet.
text("auth.failed", "These credentials do not match our records.");
The text! macro takes the arguments of the PHP helper, text($key, $default, $replace, $locale), because a Rust function has no optional arguments:
text!("key_name"); text!("key_name", "default_value"); text!("key_name", "default_value", replace! { name => "John" }); text!("key_name", "default_value", replace! { name => "John" }, "es");
In a MiniJinja view the same thing is a function:
{{ text('auth.failed', 'These credentials do not match our records.') }}
The key is stable, so you can reword the English freely. The sentence sits in the code, so you read it without opening a language file. A key missing from the language file of the current locale is looked up in the one of the fallback locale before the source text is used. If you pass only a key, the text is made from it, hello_mate becoming "Hello Mate", and the scanner writes the same text to the language files.
A function in a template escapes what it prints, as everything in MiniJinja does. Use | safe for a translation that carries HTML you wrote yourself.
Placeholders and plurals
Placeholders use Laravel's :name syntax and take a Replace, which replace! builds. They survive translation, so :name still means :name in Spanish.
text!("welcome.user", "Welcome, :name!", replace! { name => "John" });
{{ text('welcome.user', 'Welcome, :name!', {'name': user.name}) }}
A value is text, a number, a boolean, None, or a closure that wraps a <name>...</name> tag, with ReplaceValue::callback. :name, :Name and :NAME take the value as it is, with its first letter in capitals and all in capitals.
Plurals separate the forms with | and take the quantity as count, with the rules of Laravel's MessageSelector for each language:
text!("items.count", "One item|You have :count items", replace! { count => n }); text!("items.count", "{0} No items|[1,19] You have :count items|[20,*] You have plenty", replace! { count => n });
Both a | in the text and a numeric count are needed, so text("shortcut", "Ctrl|Alt") stays as it is. The translator decides how many forms each language gets, so review the result for languages with more forms than yours and lock the key once it is right.
Configuring languages and the translator
TextsConfig is the configuration section, the equivalent of config/texts.php, with the same keys and defaults in snake case. The API keys and the models read the same environment variables, and everything else is set in src/app.rs:
Application::configure().with_config(|config, _| { let texts = config.section_mut::<TextsConfig>(); texts.default_translator = "claude".to_owned(); texts.context = "A real estate CRM used by estate agents. Address the user formally.".to_owned(); texts.openai.timeout = 120; })
Four translators ship with the package. Pick one for a scan with --translator=, or make it the default with default_translator.
| Translator | --translator= |
Key in .env |
What it is |
|---|---|---|---|
| OpenAI | openai |
OPENAI_API_KEY |
OpenAI's chat models, gpt-5.4-nano unless OPENAI_MODEL says otherwise |
| Claude | claude |
ANTHROPIC_API_KEY |
Anthropic's Messages API, claude-haiku-4-5 unless ANTHROPIC_MODEL says otherwise |
| Google Translate | google |
GOOGLE_TRANSLATOR_API_KEY |
The Google Cloud Translation API |
| Translatorio | translatorio |
TRANSLATORIO_API_KEY |
A translation API that protects placeholders and tags itself |
The Claude translator runs with prompt caching, so repeated batches within a single scan reuse the cached instructions. context is a sentence about your application (what it does, the register it uses, the names it never translates) sent with every batch. Google Translate takes no prompt, so it ignores it; the other three read it. Translation keys travel with their text and are used as context too, so nav.home tells the translator that "Home" is a navigation link.
When the texts in your code are not written in the application's locale, for example an application that runs in Spanish with English source texts, name the language so the scanner compares against the right file:
texts.source_locale = Some("en".to_owned());
What each model can do
Translating with gpt-3.5-turbo is not translating with gpt-5.4-nano: one answers 4,096 tokens at most and the other 128,000, one takes temperature and another refuses any request that sends it. The OpenAI and Claude translators know the models of both providers and act on it:
- Batches are sized by the answer they produce: a batch into twenty languages answers twenty times its size, so it is cut to fit one answer of the model, and languages go in groups when one string into all of them would not fit.
- An answer cut short at the limit is split in two, never sent again whole.
- Each model gets only the parameters it accepts:
temperaturewhere it is taken,reasoning_effortfor reasoning models, a JSON schema where Structured Outputs exist. - The source language is never sent, and
pt_BRorzh_CNare written under the code you use.
A model the package does not know is asked with a 4,096-token answer and no parameter it might refuse. Correct a model or add a new one with models, by its name or a prefix of it:
use laratext::ModelOverride; texts.models.insert( "gpt-6".to_owned(), ModelOverride::new() .max_output_tokens(128_000) .temperature(false) .json("schema") .reasoning(true) .reasoning_effort("low"), );
Translating with Translatorio
Translatorio takes placeholders (:name, , %s), HTML tags and links out of the text before the model sees it and puts them back afterwards, so a translated string can never lose its :count. It reports any placeholder that did not survive, and the scan prints a warning for that key instead of writing a broken string silently.
TRANSLATORIO_API_KEY=tr_live_... TRANSLATORIO_GLOSSARY=shop TRANSLATORIO_FORMALITY=informal
laravel laratext:scan --write --translator=translatorio
Retries reuse the same idempotency key, so a retried batch is never charged twice. Running out of credits halfway keeps what was already translated, and the next scan finishes the rest.
The scan command
The scan reads your Rust files, your MiniJinja templates and the scripts of scan.scripts.paths, collects every text() call with its default, works out which keys are missing from each language, translates only those, and writes them into lang/es.json, lang/fr.json and so on.
laravel laratext:scan --write
The key must be a literal string. text(&key) works at run time if the key exists, but the scanner never sees it, so it is never created or translated. The base language is the locale of Laralocale, or source_locale; the targets are the languages in the config.
| Option | What it does |
|---|---|
--dry |
Report what a real run would do, without writing and without calling the translator |
--diff |
Show what changes |
--lang=es |
Restrict to one language |
--translator=claude |
Override the configured service |
--resync |
Retranslate every key from scratch |
--only-missing |
Translate brand-new keys only, and list the drifted ones as warnings |
--prune |
List the keys in the language files that no code uses, and with --write remove them |
By default --write translates new keys and also the drifted ones, whose source text no longer matches the language file of the source language. When a person has reviewed a translation, protect it:
laravel laratext:lock save --lang=es laravel laratext:lock "errors.*" laravel laratext:unlock save --lang=es
A locked key is never written by the scanner: not retranslated on drift, not touched by --resync, not removed by --prune. Locks live in lang/.locked/{locale}.json, so commit them.
Writing your own translator
The translation service is a trait, so you can point it at anything: a different API, a glossary-aware endpoint, a human review queue.
laravel make:translator BeautifulTranslator
That creates src/translators/beautiful_translator.rs and prints the lines to declare it. You implement translate, which turns a single string into every target language and returns them keyed by language code, and register the translator under a name:
providers.add(LaratextServiceProvider::new().translator("beautiful", || BeautifulTranslator));
Then --translator=beautiful picks it, and so does default_translator. A name that is registered again replaces the one before it, so you can swap a bundled translator for your own. Override translate_many as well when your API takes many strings per call, so a batch is one round trip instead of one call per string.
to can contain the source language. laratext:scan passes every language of languages as a target, the source language from among them, and translate receives it unless the translator returns a number from output_token_limit. The bundled translators answer from with the text as it is and never ask a service for it, and a custom one has to do the same: if language == from { results.insert(language.clone(), text.to_owned()); continue; }. PHP behaves the same way, and its make:translator stub does not warn about it either. Use laratext::translator::same_language when pt_BR and pt-br may both appear.
JavaScript: React, Vue, Svelte and Alpine
The same call works in the browser, with the same key, source text, placeholders and plurals:
text('cart.total', 'Total: :amount', { amount: '12 €' }) text('cart.items', 'One item|:count items', { count: 3 })
The scanner finds the calls in the folders you list in scan.scripts.paths, Laravel Rust hands each page only the translations it needs, and a small JavaScript module with no npm install looks them up the way text() does in Rust. The crate serves the module under /vendor/laratext/, and laravel laratext:publish copies it into your project for a bundler. On a page rendered by MiniJinja, print the translations the page needs with {{ texts(['header', 'cart']) }}. With Inertia, share Text::frontend(["header"], None) as a prop.
Testing
The translators go through the HTTP client of Laravel Rust, so client::fake() intercepts every request and nothing leaves your machine:
use laravel::http::client; let http = client::fake().with( "api.openai.com/*", json!({ "choices": [{ "message": { "content": json!({ "save": { "es": "Guardar" } }).to_string() } }] }), ); app.command("laratext:scan --write --translator=openai").await.assert_successful(); http.assert_sent_count(1);
The language files are in the base path of the application, so give each test its own with APP_BASE_PATH. Use laralocale::with_locale("es", async { .. }) to run code in a locale.
Differences from the PHP package
text()is a function of two arguments and a macro. A Rust function has no optional arguments, sotext("key", "default")is the function andtext!takes the arguments of the PHP helper.- A key alone makes its text at run time.
text('hello_mate')in PHP returns an empty string until the scanner has written the key. Here it returnsHello Mate, the text the scanner writes, so the application reads the same before and after a scan. replace!andReplacetake the place of the$replacearray. From a template the replacements are a map,{'name': name}, and a closure cannot be passed.- No Blade directives.
@textis the MiniJinja functiontext()and@textsistexts(). Like every MiniJinja expression they escape what they print. - The locale comes from Laralocale. Laravel Rust has no localization, so
App::getLocale()islaralocale::locale(). A key missing from the language file of the locale is looked up in the one of its language (ptforpt_BR) and then in the fallback locale's, the chain oflaralocale::candidates(), before the source text is used, which Laravel does not do for JSON translations. - Only JSON translations.
lang/{locale}/{group}.phpis not read. The language files are thelang/{locale}.jsonof the PHP package, in the same format. - Configuration is a typed section.
TextsConfighas the keys and defaults ofconfig/texts.php.lang_pathis new, andtexts.translatorsis not a key: translators are registered in the provider, because a name maps to Rust code. - The scanner reads Rust and MiniJinja, not PHP and Blade. It finds
text(,text!(andText::get(in.rsfiles andtext(in.htmltemplates. The script scanner is the PHP one. - The translators are traits and the HTTP client is Laravel Rust's. The bundled ones keep the request, the batching, the truncation handling and the retries of the PHP ones.
- A language file that is not valid JSON stops the scan with an error and is never overwritten. PHP read it as empty and wrote over it.
make:translatorcreatessrc/translators/{snake_case}.rsand prints the lines to declare and register it.- The JavaScript module is served and published. PHP points a Vite alias at
vendor/. Here the crate serves the module andlaratext:publishcopies it.
built and maintained by Edu Lazaro · MIT license