LoginSignup
186
195

More than 5 years have passed since last update.

Laravelのアセットに関するTips

Last updated at Posted at 2016-11-19

css, js, 画像などの読み込みはassetヘルパーを使う

asset('ファイルパス')はpublicディレクトリのパスを返す関数。
僕は以下のような構成にしてます。

public 
  |__ css
  |__ js
  |__ img
  |__ html

各ファイルの読み込み方

index.blade.php
<!-- css -->
<link rel="stylesheet" href="{{ asset('/css/bootstrap.min.css') }}">

<!-- js -->
<script src="{{ asset('/js/jquery-3.1.1.min.js') }}"></script>

<!-- img -->
<img alt="ロゴ" src="{{ asset('/img/logo.png') }}">

セキュアな通信しかしないよって場合はsecure_assetを使う

HTTPSオンリーな本番環境の場合は、asset()の代わりにsecure_assset()を使います。
で、一つここに問題が。ローカルの開発環境ではSSLでつなげないので、環境ごとに読み込み方を変えます。

index.blade.php
@if(app('env')=='local')
    <link rel="stylesheet" href="{{ asset('/css/bootstrap.min.css') }}">
    <script src="{{ asset('/js/jquery-3.1.1.min.js') }}"></script>
@endif
@if(app('env')=='production')
    <link rel="stylesheet" href="{{ secure_asset('/css/bootstrap.min.css') }}">
    <script src="{{ secure_asset('/js/jquery-3.1.1.min.js') }}"></script>
@endif

レスポンスでHTMLファイルを返したい時

routes.php
Route::get('/hoge', function() {
    return File::get(public_path() . '/html/hoge.html');
});

public_path( )はpulicディレクトリのパスを返す関数。
HTMLファイルはpulic/html下に置きます。

CSSで画像を読み込みたい時

.hoge::before {
  content: '';
  height: 16px;
  width: 16px;
  background: url("../img/hoge.svg") no-repeat center center;
 }

url( )は、指定されたパスへ、アプリのルートからドメインを含めた完全なURLを生成してくれる関数。
ちなみにsecure_url( )もあります。

186
195
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
186
195