Add translation ability for menu labels

This commit is contained in:
Kendrick Chan 2021-04-27 23:50:49 +08:00
parent 25e74dfcf9
commit 9021fe4595
2 changed files with 24 additions and 1 deletions

View file

@ -8,6 +8,7 @@ services:
autowire: true autowire: true
arguments: arguments:
$menu_data: [] $menu_data: []
$trans: "@translator"
Catalyst\MenuBundle\EventListener\MenuAnnotationListener: Catalyst\MenuBundle\EventListener\MenuAnnotationListener:
arguments: arguments:

View file

@ -7,6 +7,7 @@ use Symfony\Component\Yaml\Parser as YamlParser;
use Symfony\Component\Config\ConfigCache; use Symfony\Component\Config\ConfigCache;
use Symfony\Component\Config\Resource\FileResource; use Symfony\Component\Config\Resource\FileResource;
use Symfony\Component\Routing\RouterInterface; use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\Translation\TranslatorInterface;
use Catalyst\MenuBundle\Menu\Collection; use Catalyst\MenuBundle\Menu\Collection;
use Catalyst\MenuBundle\Menu\Item; use Catalyst\MenuBundle\Menu\Item;
@ -18,12 +19,14 @@ class Generator
protected $menu; protected $menu;
protected $menu_data; protected $menu_data;
protected $translator;
public function __construct($menu_data) public function __construct($menu_data, TranslatorInterface $trans)
{ {
$this->index = new Collection(); $this->index = new Collection();
$this->menu = new Collection(); $this->menu = new Collection();
$this->menu_data = $this->processConfigs($menu_data); $this->menu_data = $this->processConfigs($menu_data);
$this->translator = $trans;
} }
public function getMenu($menu_key) public function getMenu($menu_key)
@ -123,8 +126,27 @@ class Generator
return $pdata; return $pdata;
} }
protected function translate($text)
{
// find text enclosed in []
$regex = '/\[(.*)\]/U';
preg_match_all($regex, $text, $matches);
// replace text enclodes in [] with the trnaslation of it
$final_text = $text;
$all_terms = $matches[1];
foreach ($all_terms as $term)
{
$final_text = str_replace('[' . $term . ']', $this->translator->trans($term), $final_text);
}
return $final_text;
}
protected function newItem($index, $id, $label, $icon = null) protected function newItem($index, $id, $label, $icon = null)
{ {
$trans_label = $this->translate($label);
$mi = new Item(); $mi = new Item();
$mi->setID($id) $mi->setID($id)
->setLabel($label) ->setLabel($label)