laravel自定義模板指令-tojs

Blade 容許你自定義命令,你可使用 directive 方法註冊命令。當 Blade 編譯器遇到該命令時,它將會帶參數調用提供的回調函數。blade模板能夠經過directive方法來自定義模板指定,javascript

tojs指令主要用於PHP自定義一些數據轉換爲js對象方便js調用php

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::classjava

aliases 添加
'ToJs' => \App\Helpers\ToJs\Facades\ToJsFacade::class,json

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>app

相關文章
相關標籤/搜索