Important: The information in this article is over 12 months old, and may be out of date or no longer relevant.
But hey, you're here anyway, so give it a read see if it still applies to you.
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:
1{{ if link | is_url }}2 <a href="{{ link }}">"link" is a URL</a>3{{ /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:
1use Statamic\Facades\URL;2 3if (URL::isExternal($value)) {4 echo "yep, $value is an external URL";5}
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:
1public function isExternalUrl($value)2{3 return Str::isUrl($value) && URL::isExternal($value);4}
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:
1{{ if link | is_external_url }}2 <a href="{{ link }}" target="_blank">External, baby!</a>3{{ else }}4 <a href="{{ link }}">Keep it internal</a>5{{ /if }}
Or a little more inline, like if you were looping over a list of Links:
1<a href="{{ link }}"2 {{ if link | is_external_url }} target="_blank" {{ /if }}3 >{{ title }}</a>
Such a simple modifier, but hopefully one that helps other Statamic devs out there too!