Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hyperlink to an exterior URL retrieved from database using TWIG

I'm using Symfony 2.0.19. I'm trying to create a hyperlink to an external URL, which is retrieved from a database.

I tried doing this

<td><a href="{{dominio.url}}">{{dominio.url}}</a></td>

but the path I get is a relative path to the URL inside the base URL example "localhost/web/www.tralalalala.com" instead of just "www.tralalalala.com".

How do I do this?

like image 627
Splendonia Avatar asked Jan 05 '13 06:01

Splendonia


1 Answers

Here's a concrete example of what Pierrickouw is suggesting:

Create a Twig extension or filter under src/Twig, and call it for example ExternalLinkFilter. Define the class as follows:

<?php 

namespace AppBundle\Twig;

class ExternalLinkFilter extends \Twig_Extension
{
    public function getFilters()
    {
        return array(
            new \Twig_SimpleFilter('external_link', array($this, 'externalLinkFilter')),
        );
    }

    /* source: http://stackoverflow.com/a/2762083/3924118 */
    public function externalLinkFilter($url)
    {
        if (!preg_match("~^(?:f|ht)tps?://~i", $url)) {
            $url = "http://" . $url;
        }

        return $url;
    }

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

?>

Now, you should register this class as a service in config/services.yml as follows:

services:

    # other services

    app.twig.external_link:
        class: AppBundle\Twig\ExternalLinkFilter
        public: false
        tags:
            - { name: twig.extension }

Now you can simply use the filter called external_link as you would use any Twig's default one, e.g.:

...

<a href="{{check.hostname | external_link }}"> {{check.hostname}}</a>

...
like image 176
nbro Avatar answered Nov 08 '22 14:11

nbro