Hyperlink to an external URL retrieved from the database using TWIG

I am using Symfony 2.0.19. I am trying to create a hyperlink to an external url that is retrieved from a database.

I tried to do it

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

but the path I get is the relative path to the url inside the base url of "localhost / web / www.tralalalala.com" and not just "www.tralalalala.com".

How to do it?

+4
source share
2 answers

I suggest you create your own Twig filter.

If your url already has http:// , do not add it, otherwise add it.

Check here for instructions.

+3
source

Here is a concrete example of what PierricΓ³w offers:

Create an extension or Twig filter in 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'; } } ?> 

You should now 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 just use a filter called external_link , since you would use any default Twig by default, for example:

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

All Articles