Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add more flexible asset attributes #418

Merged
merged 3 commits into from
Mar 11, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading