Skip to content

Commit 2ef8bac

Browse files
authored
[5.x] Add optional fallback for missing keys in {{ trans }} tag (statamic#11944)
1 parent 426ae8a commit 2ef8bac

File tree

2 files changed

+21
-1
lines changed

2 files changed

+21
-1
lines changed

src/Tags/Trans.php

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,8 +13,14 @@ public function wildcard($tag)
1313
{
1414
$key = $this->params->get('key', $tag);
1515
$locale = $this->params->pull('locale') ?? $this->params->pull('site');
16+
$fallback = $this->params->get('fallback');
1617
$params = $this->params->all();
1718

18-
return __($key, $params, $locale);
19+
$translation = __($key, $params, $locale);
20+
if ($fallback && $translation === $key) {
21+
return __($fallback, $params, $locale);
22+
} else {
23+
return $translation;
24+
}
1925
}
2026
}

tests/Tags/TransTagTest.php

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,4 +38,18 @@ public function it_translates_to_specific_locale()
3838
$this->assertEquals('Bonjour, Bob', $this->parse('{{ trans key="package::messages.hello_name" name="Bob" locale="fr" }}'));
3939
$this->assertEquals('Bonjour, Bob', $this->parse('{{ trans key="package::messages.hello_name" name="Bob" site="fr" }}'));
4040
}
41+
42+
#[Test]
43+
public function it_falls_back_to_fallback_for_missing_key()
44+
{
45+
$this->assertEquals('Fallback', $this->parse('{{ trans key="package::messages.does_not_exist" fallback="Fallback" }}'));
46+
$this->assertEquals('Bonjour', $this->parse('{{ trans key="package::messages.does_not_exist" fallback="package::messages.hello" locale="fr" }}'));
47+
}
48+
49+
#[Test]
50+
public function it_applies_replacement_to_fallbacks()
51+
{
52+
$this->assertEquals('Fallback Bob', $this->parse('{{ trans key="package::messages.does_not_exist" name="Bob" fallback="Fallback :name" }}'));
53+
$this->assertEquals('Bonjour, Bob', $this->parse('{{ trans key="package::messages.does_not_exist" name="Bob" fallback="package::messages.hello_name" locale="fr" }}'));
54+
}
4155
}

0 commit comments

Comments
 (0)