下面由Laravel教學專欄為大家介紹laravel自訂範本指令-tojs ,希望對需要的朋友有幫助!
Blade 允許你自訂指令,你可以使用 directive 方法註冊指令。當 Blade 編譯器遇到該指令時,它將會帶著參數呼叫提供的回呼函數。 blade範本可以透過directive方法來自訂範本指定,
tojs指令主要用於PHP自訂一些資料轉換為js物件方便js呼叫
<?php namespace App\Providers; use App\Helpers\ToJs\ToJs; use Illuminate\Support\Facades\Blade; use Illuminate\Support\ServiceProvider; class ToJsServiceProvider extends ServiceProvider { /** * Bootstrap the application services. * * @return void */ public function boot() { // } /** * Register the application services. * * @return void */ public function register() { $this->app->singleton('tojs', function () { return new ToJs(); }); /* * The block of code inside this directive indicates * the chosen javascript variables. */ Blade::directive('tojs', function () { return '<script> window.Laravel = ' . json_encode(app('tojs')->get()) . '</script>'; }); } }
<?php namespace App\Helpers\ToJs; use Illuminate\Support\Arr; class ToJs { protected $data = []; public function put(array $data) { foreach ($data as $key => $value) { $this->data[$key] = value($value); } return $this; } public function get($key = null, $default = null) { if (!$key) return $this->data; return Arr::get($this->data, $key, $default); } public function forget($keys) { Arr::forget($this->data, $keys); return $this; } }
namespace App\Helpers\ToJs\Facades; use Illuminate\Support\Facades\Facade; class ToJsFacade extends Facade { /** * Get the registered name of the component. * * @return string */ protected static function getFacadeAccessor() { return 'tojs'; } }
providers 新增\App\Providers\ToJsServiceProvider::class
aliases 加入'ToJs' => \App\Helpers\ToJs\Facades\ToJsFacade::class,
if (!function_exists('to_js')) { /** * Access the javascript helper. */ function to_js($key = null, $default = null) { if (is_null($key)) { return app('tojs'); } if (is_array($key)) { return app('tojs')->put($key); } return app('tojs')->get($key, $default); } }
在PHP程式碼需要的地方呼叫to_js(['username'=>'test'] );
blade模板直接透過@tojs
就可以在頁面渲染出<script> window.Laravel = {"username":"test "}</script>
以上是關於laravel自訂範本指令-tojs的詳細內容。更多資訊請關注PHP中文網其他相關文章!