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?
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>
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With