Last active
August 14, 2020 06:10
-
-
Save pryley/782c2653fe0245099f671a959adaa8a0 to your computer and use it in GitHub Desktop.
Add additional attribute to non-local links
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<a href="{{ link }}"{{ if not link | is_local_url }} rel="noopener" target="_blank"{{ /if }}> | |
{{ label }} | |
</a> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Modifiers; | |
use Illuminate\Support\Str; | |
use Statamic\Modifiers\Modifier; | |
class IsLocalUrl extends Modifier | |
{ | |
/** | |
* Modify a value. | |
* | |
* @param mixed $value The value to be modified | |
* @param array $params Any parameters used in the modifier | |
* @param array $context Contextual values | |
* @return mixed | |
*/ | |
public function index($value, $params, $context) | |
{ | |
if (Str::startsWith($value, 'http')) { | |
return Str::contains($value, request()->root()); | |
} | |
return true; | |
} | |
} |
Passing null to the strncmp
string function (which is what Str uses under the hood) will not throw an Exception.
You can always cast the value to a string if you prefer:
Str::startsWith((string) $value, 'http')
Ah didn't know that - thx for providing that information :-)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
i recommend a null check otherwise that might cause a exception