12

I want to render an HTML label like:

$menu->addChild('Dashboard', array(
    'route' => 'dashboard', 
    'label' => '<i class="fa-icon-bar-chart"></i><span class="hidden-tablet"> Dashboard</span></a>',
    'extra' => array('safe_label' => true)
    )
);

And I've pass the proper option while rendering:

{{ knp_menu_render('WshCmsHtmlBundle:Builder:mainMenu', {'allow_safe_labels': true} ) }}

But my label is still being escaped. What am I doing wrong?

FyodorX
  • 1,490
  • 2
  • 19
  • 23
Bartosz Rychlicki
  • 1,918
  • 3
  • 20
  • 41
  • I tried your question and it's the answer for me and work with me perfectly with route :) thanks – HMagdy Jan 14 '15 at 12:02

3 Answers3

17

Ok, the answer is!

You set up extra items on menu item not by 'extra' key but by 'extras' key. So when you setup the item like this:

$menu->addChild('Dashboard', array(
    'route' => 'dashboard', 
    'label' => '<i class="fa-icon-bar-chart"></i><span class="hidden-tablet"> Dashboard</span></a>',
    'extras' => array('safe_label' => true)
)
);

it works fine!

Bartosz Rychlicki
  • 1,918
  • 3
  • 20
  • 41
  • Ahh, we normally use the setExtra method instead of the array initialization. Good catch on the missing 's' for extras! – Ken Hannel Apr 24 '13 at 23:58
  • 6
    I just did this on a project and it's worth noting that in order for it to work BOTH safe_label options need to be set in the factory and the view. ('extras' => array('safe_label' => true) & {'allow_safe_labels': true} – jfgrissom Jun 19 '14 at 18:33
11

There's two steps to achieve this.

1. MenuBuilder

You have to set safe_label to true in extras. Note that you can now write HTML in your label.

$menu->addChild('Home<i><b></b></i>', array(
    'route' => 'homepage',
    'extras' => array(
        'safe_label' => true
    ),
));

2. Twig

You have to filter the output of knp_menu_render() so that it prints raw HTML (see documentation).

{{ knp_menu_render('main', {'allow_safe_labels': true}) | raw }}

Warning

Please be aware that this may be dangerous. From the documentation:

Use it with caution as it can create some XSS holes in your application if the label is coming from the user.

FyodorX
  • 1,490
  • 2
  • 19
  • 23
1

I used FyodorX's method to add a strong tag. It works like a charm but I must say that the raw filter is not necessary

Bevelopper
  • 75
  • 1
  • 9