Blade 许可你自定义敕令,你能够运用 directive 要领注册敕令。当 Blade 编译器碰到该敕令时,它将会带参数挪用供应的回调函数。blade模板能够经由过程directive要领来自定义模板指定,
tojs指令重要用于PHP自定义一些数据转换为js对象轻易js挪用
1.建立ToJsServiceProvider
<?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';
}
}
4.在config数组增加serviceProvider
providers 增加\App\Providers\ToJsServiceProvider::class
aliases 增加'ToJs' => \App\Helpers\ToJs\Facades\ToJsFacade::class,
5.为了轻易挪用能够在写一个helper要领
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>