Twig filter return inside html tag
Thanks to @Ilya Yarkovets I've found way to solve that problem. All I needed to do is to change $title by making this:
$title = html_entity_decode(str_replace(' ', ' ', $title));return ' data-toggle=tooltip data-placement=top title='.($title).' ';
&thinsp was better than   because of text-wrapping.
Thanks to the dynamic Twig filters you can simplify the code of your extension as follows:
class TooltipExtension extends \Twig_Extension{ public function getFilters() { return array( new \Twig_SimpleFilter('tooltip', array($this, 'tooltip',['is_safe'=>['html']])), new \Twig_SimpleFilter('tooltip_*', array($this, 'positionedTooltip', ['is_safe'=>['html']])), ); } public function tooltip($title) { return $this->positionedTooltip('top', $title); } public function positionedTooltip($position, $title) { $validPositions = ['top', 'bottom', 'left', 'right']; if (!in_array($position, $validPositions)) { throw new \InvalidArgumentException(sprintf('The position of the tooltip can only be one of the following: %s', implode(', ', $validPositions))); } return sprintf(' data-toggle=tooltip data-placement=%s title="%s" ', $position, $title); } public function getName() { return 'tooltip_extension'; }}