Let's assume you already have a working translation system.
At first, you need to create a template which extends knp_menu.html.twig
and adds the Twig trans
filter. In this example, the template is located
at src/AppBundle/Resources/views/Default/knp_menu.html.twig
. It allows changing
the domain and the parameters for the translator through the extras of the item.
{% extends 'knp_menu.html.twig' %}
{% block label %}
{{ item.label|trans(
item.getExtra('translation_params', {}),
item.getExtra('translation_domain', 'messages')
) }}
{% endblock %}
If you want to translate all of your menus, change the default template:
# app/config/config.yml
knp_menu:
twig:
template: AppBundle:Default:knp_menu.html.twig
If you want to translate a certain menu, add the template
parameter to
its knp_menu_render
call.
{{ knp_menu_render('name_of_your_menu', {'template': 'AppBundle:Default:knp_menu.html.twig'}) }}
That's it.
In your menu Builder class you need to add extras. For example, imagine you have two menu items Home and Login.
$menu = $factory->createItem('root');
$menu->addChild('Home', array('route' => 'homepage'));
$menu->addChild('Login', array('route' => 'login'));
To translate them you need to add translation_domain parameter using setExtra(s):
$menu = $factory->createItem('root');
// will look for "Home" in AppBundle/Resources/translations/AppBundle.locale.yml
$menu->addChild('Home', array('route' => 'homepage'))->setExtra('translation_domain', 'AppBundle');
// will look for "Login" in Acme/AdminBundle/Resources/translations/AcmeAdminBundle.locale.yml
$menu->addChild('Login', array('route' => 'login'))->setExtra('translation_domain', 'AcmeAdminBundle');