Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to disable HTML escaping of labels in KnpMenuBundle

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?

like image 732
Bartosz Rychlicki Avatar asked Apr 22 '13 16:04

Bartosz Rychlicki


3 Answers

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!

like image 183
Bartosz Rychlicki Avatar answered Nov 12 '22 04:11

Bartosz Rychlicki


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.

like image 11
FyodorX Avatar answered Nov 12 '22 04:11

FyodorX


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

like image 1
Bevelopper Avatar answered Nov 12 '22 03:11

Bevelopper