Skip to content

Commit

Permalink
Add more flexible asset attributes (lonnieezell#418)
Browse files Browse the repository at this point in the history
* Add aditional attribute inclusion functionality

* Some fixes

* minor style imrovements
  • Loading branch information
dgvirtual authored Mar 11, 2024
1 parent bd1b1bf commit cfb5ebe
Showing 1 changed file with 30 additions and 10 deletions.
40 changes: 30 additions & 10 deletions src/Assets/Helpers/assets_helper.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,35 +8,55 @@
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
if (! defined('asset_link')) {
if (!defined('asset_link')) {
/**
* Generates the URL to serve an asset to the client
*
* @param string $type css, js
* @param string $location url to asset file
* @param string $type css, js
* @param mixed $attributes Additional attributes to include in the asset link tag.
* Can be provided as a string (for value-less attributes like "defer")
* or an associative array of attribute-value pairs.
* Defaults to null.
*/
function asset_link(string $location, string $type, bool $preload=false): string
function asset_link(string $location, string $type, mixed $attributes = null): string
{
$url = asset($location, $type);

$tag = '';
$relationString = $preload
? 'rel="preload" as="' . ($type === 'css' ? 'style' : 'script') . '"'
: ($type === 'css' ? "rel='stylesheet'" : '');

$additionalAttr = '';
$defaultAttr = $type === 'css' ? "rel='stylesheet'" : '';

if (is_string($attributes)) {
$additionalAttr = $attributes;
}
if (is_array($attributes)) {
foreach ($attributes as $key => $value) {
// if the array already includes the 'rel', remove the default
if ($key === 'rel') {
$defaultAttr = '';
}
$additionalAttr .= "{$key}='{$value}' ";
}
}

$additionalAttr .= $defaultAttr;

switch ($type) {
case 'css':
$tag = "<link href='{$url}' {$relationString} />";
$tag = "<link href='{$url}' {$additionalAttr} />";
break;

case 'js':
$tag = "<script src='{$url}' {$relationString}></script>";
$tag = "<script src='{$url}' {$additionalAttr}></script>";
}

return $tag;
}
}

if (! defined('asset')) {
if (!defined('asset')) {
function asset(string $location, string $type): string
{
$config = config('Assets');
Expand Down Expand Up @@ -78,7 +98,7 @@ function asset(string $location, string $type): string

$filetime = filemtime($path);

if (! $filetime) {
if (!$filetime) {
throw new \RuntimeException('Unable to get modification time of asset file: ' . $filename);
}
$fingerprint = $separator . $filetime;
Expand Down

0 comments on commit cfb5ebe

Please sign in to comment.