Search code examples
twitter-bootstrapsymfonytwigtwitter-bootstrap-tooltiptwig-extension

Twig filter return inside html tag


I am trying to display an Bootstrap tooltip much easier and cleaner inside twig template. I want to achieve something like this: <i class="icon" {{'this is great tooltip'|tooltip}}></i> I've created twig filter:

class TooltipExtension extends \Twig_Extension{

    public function getFilters()
    {
        return array(
            new \Twig_SimpleFilter('tooltip', array($this, 'tooltipFilter',['is_safe'=>['html']])),
            new \Twig_SimpleFilter('tooltip_top', array($this, 'tooltipTopFilter')),
            new \Twig_SimpleFilter('tooltip_bottom', array($this, 'tooltipBottomFilter')),
            new \Twig_SimpleFilter('tooltip_left', array($this, 'tooltipLeftFilter')),
            new \Twig_SimpleFilter('tooltip_right', array($this, 'tooltipRightFilter')),
        );
    }

    public function tooltipFilter($title, $direction = "top")
    {
        switch($direction){
            case "top":
                return $this->tooltipTopFilter($title);

            case "bottom":
                return $this->tooltipBottomFilter($title);

            case "left":
                return $this->tooltipLeftFilter($title);

            case "right":
                return $this->tooltipRightFilter($title);

        }
    }

    public function tooltipTopFilter($title)
    {
        return ' data-toggle=tooltip data-placement=top title="'.$title.'" ';
    }

    public function tooltipBottomFilter($title)
    {
        return ' data-toggle=tooltip data-placement=bottom title='.$title.' ';
    }

    public function tooltipLeftFilter($title)
    {
        return ' data-toggle=tooltip data-placement=left title='.$title.' ';
    }

    public function tooltipRightFilter($title)
    {
        return ' data-toggle=tooltip data-placement=right title='.$title.' ';
    }

    public function getName()
    {
        return 'tooltip_extension';
    }
}

It returns string just as I want to be. But, in html code it looks like this:

<i data-original-title="&quot;this" class="icon" data-toggle="tooltip" data-placement="top" title="" is="" great="" tooltip&quot;=""></i>

As you can see, I've added ['is_safe'=>['html']] but it doesn't changed anything at all.
I was trying to change space to hard-space but without effect.
What is worse, tooltip displays like that: that tooltip is very strange ignoring all spaces and quotation marks or apostrophes. It should looks like this: this is a very good tooltip!
Please, help me how to fix it! :)


Solution

  • 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(' ', '&thinsp;', $title));
    return ' data-toggle=tooltip data-placement=top title='.($title).' ';
    

    &thinsp was better than &nbsp because of text-wrapping.