Laravel
Needing to recognise external links in Antlers led me to contribute a small modifier, bringing Statamic’s existing URL checks into templates for straightforward conditional links and attributes.
This post talks about the is_external_url modifier which became available in Statamic 4.9.0, released June 2023.
When building your site's layout with Antlers in Statamic, there are dozens of modifiers available to help either modify a variable, or also perform checks or tests against its value.
One such modifier is the is_url modifier that allows you to perform a check as part of a conditional statement to test if the value is indeed a URL:
{{ if link | is_url }}
<a href="{{ link }}">"link" is a URL</a>
{{ /if }}
And within Statamic's facades is a URL Facade for all things URL - making slugs, making a URL absolute (or relative), and also checking if a value is an external URL:
use Statamic\Facades\URL;
if (URL::isExternal($value)) {
echo "yep, $value is an external URL";
}
The problem though: we can't use that PHP-based facade within Antlers.
So here's an idea... given Statamic is so easy to extend, why not create my own modifier? Well, I did. But also... because the Statamic team are so awesome at engaging and utilising community PRs, why not make a pull request and make this a core modifier? Surely I can't be the only person who needs to test if a URL is external within Antlers.
And I did just that... a pull request submitted, function renamed (I get it... I'd naturally call it that but thought it may be good to be more URL-centric, but no, be natural next time Marty), merged and now deployed.
If you update to 4.9.0, released June 26th 2023, you'll now have access to the new `is_external_url` modifier.
What does it do? It simply returns true when the variable is an external URL.
Within Statamic's src/Modifiers/CoreModifiers.php, the new isExternalUrl has been added:
public function isExternalUrl($value)
{
return Str::isUrl($value) && URL::isExternal($value);
}
All we're doing here is ensuring:
the value is a URL, and
the URL is external
When both tests pass, you'll get true back. If either of these conditions fails, the result will be false.
You would use this in a conditional to check if the variable, such as link, is external:
{{ if link | is_external_url }}
<a href="{{ link }}" target="_blank">External, baby!</a>
{{ else }}
<a href="{{ link }}">Keep it internal</a>
{{ /if }}
Or a little more inline, like if you were looping over a list of Links:
<a href="{{ link }}"
{{ if link | is_external_url }} target="_blank" {{ /if }}
>{{ title }}</a>
Such a simple modifier, but hopefully one that helps other Statamic devs out there too!