在Laravel的@if語句中如何取得目前URL?

PHPz
發布: 2023-08-23 14:14:02
轉載
964 人瀏覽過

在Laravel的@if語句中如何取得目前URL?

要取得目前URL,可以使用下面範例中解釋的方法−

範例1

<?php namespace AppHttpControllers; use IlluminateHttpRequest; use AppModelsUser; use IlluminateHttpResponse; class UserController extends Controller { public function index(Request $request) { return view('test'); } } 
登入後複製

test.blade.php 是−

<!DOCTYPE html> <html> <head> <style> body {
         font-family: 'Nunito', sans-serif;
      } </style> </head> <body class="antialiased"> <div> @if (Request::path() == 'users') <h1>The path is users</h1> @endif </div> </body> </html> 
登入後複製

test.blade.php 檔案中,使用 Request::path() 來檢查是否指向用戶,然後只顯示 h1 標籤。 Request::path() 傳回目前正在使用的 URL

範例2

在這個範例中,讓我們使用 url()->current() 方法,如下面的範例所示。 url()->current() 傳回目前URL的完整路徑。

<?php namespace AppHttpControllers; use IlluminateHttpRequest; use AppModelsUser; class UserController extends Controller { public function index(Request $request) { return view('test'); } } 
登入後複製
登入後複製

Test.blade.php

<!DOCTYPE html> <html> <head> <style> body {
         font-family: 'Nunito', sans-serif;
      } </style> </head> <body class="antialiased"> <div> @if (url()->current() == 'http://localhost:8000/users') <h1>The path is users</h1> @endif </div> </body> </html> 
登入後複製

執行上面的範例時,它會在瀏覽器上列印以下內容−

The path is users
登入後複製
登入後複製
登入後複製

範例3

在這個範例中,我們將使用 Request::url()。它的輸出與 url()->current() 相同,它會傳回完整的URL,如下面的範例所示−

<?php namespace AppHttpControllers; use IlluminateHttpRequest; use AppModelsUser; class UserController extends Controller { public function index(Request $request) { return view('test'); } } 
登入後複製
登入後複製

Test.blade.php

<!DOCTYPE html> <html> <head> <style> body { font-family: 'Nunito', sans-serif; } </style> </head> <body class="antialiased"> <div> @if (Request::url() == 'http://localhost:8000/users') <h1>The path is users</h1> @endif </div> </body> </html> 
登入後複製

執行上面的範例時,它會在瀏覽器上列印以下內容−

The path is users
登入後複製
登入後複製
登入後複製

範例4

使用 Request::is()

<?php namespace AppHttpControllers; use IlluminateHttpRequest; use AppModelsUser; class UserController extends Controller{ public function index(Request $request) { return view('test'); } } 
登入後複製

Test.blade.php

<!DOCTYPE html> <html> <head> <style> body { font-family: 'Nunito', sans-serif; } </style> </head> <body class="antialiased"> <div> @if (Request::is('users')) <h1>The path is users</h1> @endif </div> </body> </html> 
登入後複製

在上面的範例中,Request::is() 被使用。它會傳回 true/false,表示給定的字串是否存在於 URL 中。

執行上面的範例時,它會在瀏覽器上列印以下內容−

The path is users
登入後複製
登入後複製
登入後複製


#

以上是在Laravel的@if語句中如何取得目前URL?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:tutorialspoint.com
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!