mediactive-digital/laravel-asset-aliases

在 Laravel Blade 模板中链接 CSS / JS 文件

v0.4 2019-04-16 16:31 UTC

This package is auto-updated.

Last update: 2024-09-17 04:58:26 UTC


README

此软件包使得在 Laravel Blade 模板中链接 CSS / JS 文件变得简单。

安装

使用 Composer 安装此包。

composer require mediactive-digital/laravel-asset-aliases

Laravel < 5.5

将服务提供者添加到 /config/app.php 文件。

'providers' => [
    // ...
	MediactiveDigital\LaravelAssetAliases\LaravelAssetAliasesServiceProvider::class,
],

将 AssetManager 门面添加到 /config/app.php 文件。

'aliases' => [
    // ...
    'MDAsset' => MediactiveDigital\LaravelAssetAliases\LaravelAssetAliasesFacade::class,
],

.htaccess 的更改

为了避免缓存问题,尤其是与 nginx 相关,此包会在 js & css 文件的文件名中添加特定的时间戳。例如,home.js 将被命名为 home.{timestamp}.js。您需要在 .htaccess 文件中添加以下规则。

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteRule ^(.*)\.[0-9]+\.(css|js)$ /$1.$2 [L]
</IfModule>

使用方法

您可以链接内部资源或外部 URL。

链接 CSS 文件。

单个文件

	{!! MDAsset::addCss('stylesheet.css') !!}

或文件数组

	{!! MDAsset::addCss(['stylesheet.css', 'stylesheet2.css']) !!}

通过别名链接 JS 文件。

单个文件

	{!! MDAsset::addJs('script.js') !!}

或文件数组

	{!! MDAsset::addJs(['script.js', 'script2.js']) !!}

通过别名链接 CSS / JS 文件。

将别名添加到位于 /config/laravel-asset-aliases/alias.php 的配置文件。

// Example
return [
	'css' => [
		'stylesheet' => 'stylesheet.css'
	],
	'js' => [
		'script' => 'script.js'
	]
];

然后通过别名链接文件,例如

	{!! MDAsset::addCss('stylesheet') !!}

HTML 属性支持。

您可以传递任意数量的 HTML 属性与文件定义一起。
这可以在配置文件和/或 Blade 模板中完成。
在 Blade 模板中定义的属性会覆盖配置中的属性。

如果您这样做,则必须使用包含必选键 "file" 和 "attributes" 的关联数组。
"file" 是您的文件(字符串),“attributes” 是您的 HTML 属性(数组)。

// Examples

// Inside configuration file : 
return [
	'css' => [
		'stylesheet' => [
			'file' => 'stylesheet.css',
			'attributes' => [
				'media' => 'print',
				'title' => 'title'
			]
		],
		'other-stylesheet' => [
			'file' => 'other-stylesheet.css',
			'attributes' => [
				'media' => 'screen'
			]
		]
	],
	'js' => [
		'script' => [
			'file' => 'script.js',
			'attributes' => [
				'integrity' => 'sha384-rAnDoMkeY',
        		'crossorigin' => 'anonymous'
			]
		],
		'other-script' => [
			'file' => 'other-script.js',
			'attributes' => [
				'async' => null
			]
		]
	]
];

// Inside Blade template : 
{!! MDAsset::addCss([
	[
		'file' => 'stylesheet', 
		'attributes' => [
			'media' => 'print',
			'title' => 'title'
		]
	], 
	[
		'file' => 'other-stylesheet', 
		'attributes' => [
			'media' => 'screen'
		]
	]
]) !!}

{!! MDAsset::addJs([
	[
		'file' => 'script.js', 
		'attributes' => [
			'integrity' => 'sha384-rAnDoMkeY', 
			'crossorigin' => 'anonymous'
		]
	], 
	'other-script' => [
		'file' => 'other-script.js',
		'attributes' => [
			'async' => null
		]
	]
]) !!}