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')), ); } 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> ...
source share