laravel assetÉèÖÃ
laravelÊÇÒ»ÖÖ³£ÓõÄphp¿ò¼Ü£¬ÆäÓÅ»¯ÁË¿ª·¢Àú³Ì²¢ÌṩÁËÐí¶àÓÐÓõĹ¦Ð§¡£ÆäÖУ¬asset()º¯ÊýÊÇÓÃÓÚÌìÉúcssºÍjavascriptÎļþµÄurlµÄº¯Êý¡£ÔÚÕâƪÎÄÕÂÖУ¬ÎÒÃǽ«ÌÖÂÛÔõÑùÔÚlaravelÖÐÓÐÓÃÉèÖÃasset()º¯Êý£¬ÒÔÀû±ã¿ª·¢¡£
Ò»Ñùƽ³£À´Ëµ£¬asset()º¯ÊýÓÃÓÚÌìÉúURL£¬ÒÔ±ã»á¼ûCSSºÍJavaScriptÎļþ¡£ÕâÊÇÓÉÓÚÔÚLaravelÖУ¬ËüÃÇͨ³£ÊÇ´æ´¢ÔÚpublicÎļþ¼ÐÖеġ£
µ«ÓÐʱ¼ä£¬ÎÒÃÇÐèÒª½«ÕâЩÎļþ´æ´¢ÔÚ²î±ðµÄλÖá£Õâʱ£¬ÎÒÃÇÐèÒª¶Ôasset()º¯Êý¾ÙÐÐһЩ×Ô½ç˵ÉèÖá£
Ê×ÏÈ£¬ÈÃÎÒÃÇ¿ìËÙÏàʶһÏÂasset()º¯ÊýµÄ»ù±¾Óï·¨£º
asset('path/to/file')
µÇ¼ºó¸´ÖÆ
ÆäÖУ¬’path/to/file’Ö¸µÄÊÇÎļþÏà¹ØÓÚpublicÎļþ¼ÐµÄ·¾¶¡£ÀýÈ磬ÈôÊÇÎÒÃÇÏëÒýÓô洢ÔÚpublic/css/main.cssÖеÄCSSÎļþ£¬ÎÒÃÇ¿ÉÒÔʹÓÃÒÔÏ´úÂ룺
asset('css/main.css')
µÇ¼ºó¸´ÖÆ
¿ÉÊÇ£¬ÈôÊÇÎÒÃÇÏ뽫CSSÎļþ´æ´¢ÔÚpublic/css/app/main.cssÖУ¬ÎÒÃǸÃÈçÄÇÀïÖÃÄØ£¿ÔÚÕâÖÖÇéÐÎÏ£¬ÄãÐèÒªÉèÖÃasset()º¯Êý£¬ÒÔ±ãÄܹ»×¼È·ÒýÓøÃÎļþ¡£
ÔÚLaravelÖУ¬ÎÒÃÇ¿ÉÒÔÔÚconfig/app.phpÎļþÖÐÉèÖÃasset_urlÑ¡Ïî¡£ÈôÊÇÎÒÃǽ«¸ÃÑ¡ÏîÉèÖÃΪ×Ô½ç˵·¾¶£¬ÄÇôasset()º¯ÊýµÄÌìÉúURLÒ²½«Ê¹Óø÷¾¶¡£
ÀýÈ磬ÈôÊÇÎÒÃÇÏ뽫asset()º¯Êý½¨ÉèµÄURLǰ׺ÉèÖÃΪ¡°/assets¡±£¬ÎÒÃÇ¿ÉÒÔÔÚconfig/app.phpÎļþÖн«asset_urlÑ¡ÏîÉèÖÃΪÒÔÏ´úÂ룺
'asset_url' => '/assets',
µÇ¼ºó¸´ÖÆ
Õâ»áʹasset()º¯ÊýÌìÉúµÄCSSºÍJavaScriptÎļþURL±äΪ£º
/assets/css/main.css
µÇ¼ºó¸´ÖÆ
ÈôÊÇÎÒÃÇÏë½øÒ»²½×Ô½ç˵URL£¬ÎÒÃÇ¿ÉÒÔ˼Á¿Ê¹ÓÃLaravelÌṩµÄ·Óɹ¦Ð§¡£
Ê×ÏÈ£¬ÎÒÃÇÐèÒª½¨ÉèÒ»¸öеķÓÉ£º
Route::get('/css/{file}', function ($file) { $path = public_path() . '/css/' . $file; if (!file_exists($path)) { return response()->make('File not found', 404); } $fileContents = file_get_contents($path); return response($fileContents, 200) ->header('Content-Type', 'text/css'); })->where('file', '.*.css$');
µÇ¼ºó¸´ÖÆ
ÔÚÕâ¸ö·ÓɵĴúÂëÖУ¬ÎÒÃÇʹÓÃpublic_path()º¯ÊýÈ·¶¨´æ´¢CSSÎļþµÄ¾ø¶Ô·¾¶£¬²¢¼ì²é¸ÃÎļþÊÇ·ñ±£´æ¡£ÈôÊÇÕÒ²»µ½¸ÃÎļþ£¬Ôò·µ»ØÒ»¸öHTTP 404ÏìÓ¦¡£²»È»£¬ÎÒÃÇʹÓÃresponse()º¯Êý½«ÎļþÄÚÈÝ·µ»Ø¸øÓû§£¬²¢ÉèÖÃContent-TypeͷΪtext/css¡£
×îºó£¬ÎÒÃÇ¿ÉÒÔʹÓÃÒÔÏ´úÂëÔÚÊÓͼÖÐÒýÓøÃÎļþ£º
<link rel="stylesheet" href="{{ url('/css/main.css') }}">
µÇ¼ºó¸´ÖÆ
ÔÚÕâ¸öʾÀýÖУ¬ÎÒÃÇʹÓÃurl()º¯ÊýÌìÉúCSSÎļþµÄURL£¬²¢½«ÆäǶÈëHTMLÒ³ÃæÖС£Õ⽫ʹÓÃÎÒÃÇÉÏÃæËù½ç˵µÄ·ÓÉÀ´¶¯Ì¬µØÌṩCSSÎļþ¡£
×ÜÌå¶øÑÔ£¬LaravelµÄasset()º¯ÊýÊÇÒ»¸öºÜÊÇÓÐÓõĹ¦Ð§£¬Ëü¿ÉÒÔ×ÊÖúÎÒÃÇÇáËɵØÖÎÀíCSSºÍJavaScriptÎļþ¡£Í¨¹ý¶Ôasset_urlÑ¡Ïî¾ÙÐÐ×Ô½ç˵ÉèÖã¬ÎÒÃÇ¿ÉÒÔ¸üºÃµØ¿ØÖÆÎļþµÄ´æ´¢Î»ÖᣱðµÄ£¬Ê¹ÓÃLaravelµÄ·Óɹ¦Ð§£¬ÎÒÃÇ¿ÉÒÔΪÎļþURLÌṩԽ·¢¶¯Ì¬µÄ»á¼û·½·¨£¬Ê¹ÆäÔ½·¢ÎÞаºÍÒ×Óá£
ÒÔÉϾÍÊÇlaravel assetÉèÖõÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡