<?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>';
});
}
}
2. ToJs方法主要是对数组的一些操作
<?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;
}
}
3.声明facade
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';
}
}
<?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>';
});
}
}
2. ToJs方法主要是对数组的一些操作
<?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;
}
}
3.声明facade
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';
}
}