Skip to content

Latest commit

 

History

History
74 lines (49 loc) · 2.29 KB

i18n.rst

File metadata and controls

74 lines (49 loc) · 2.29 KB

I18n for your menu labels

Let's assume you already have a working translation system.

Create the template

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 %}

Include the template

Alternative A: I18n for all menus

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

Alternative B: I18n only for certain menus

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.

Add translation domain information in the controller

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');