当前位置:Gxlcms > php框架 > 关于laravel自定义模板指令-tojs

关于laravel自定义模板指令-tojs

时间:2021-07-01 10:21:17 帮助过:32人阅读

下面由Laravel教程栏目给大家介绍laravel自定义模板指令-tojs ,希望对需要的朋友有所帮助!

Blade 允许你自定义命令,你可以使用 directive 方法注册命令。当 Blade 编译器遇到该命令时,它将会带参数调用提供的回调函数。blade模板可以通过directive方法来自定义模板指定,

tojs指令主要用于PHP自定义一些数据转换为js对象方便js调用

1.创建ToJsServiceProvider

  1. <?php
  2. namespace App\Providers;
  3. use App\Helpers\ToJs\ToJs;
  4. use Illuminate\Support\Facades\Blade;
  5. use Illuminate\Support\ServiceProvider;
  6. class ToJsServiceProvider extends ServiceProvider
  7. {
  8. /**
  9. * Bootstrap the application services.
  10. *
  11. * @return void
  12. */
  13. public function boot()
  14. {
  15. //
  16. }
  17. /**
  18. * Register the application services.
  19. *
  20. * @return void
  21. */
  22. public function register()
  23. {
  24. $this->app->singleton('tojs', function () {
  25. return new ToJs();
  26. });
  27. /*
  28. * The block of code inside this directive indicates
  29. * the chosen javascript variables.
  30. */
  31. Blade::directive('tojs', function () {
  32. return '<script> window.Laravel = ' . json_encode(app('tojs')->get()) . '</script>';
  33. });
  34. }
  35. }

2. ToJs方法主要是对数组的一些操作

  1. <?php
  2. namespace App\Helpers\ToJs;
  3. use Illuminate\Support\Arr;
  4. class ToJs
  5. {
  6. protected $data = [];
  7. public function put(array $data)
  8. {
  9. foreach ($data as $key => $value) {
  10. $this->data[$key] = value($value);
  11. }
  12. return $this;
  13. }
  14. public function get($key = null, $default = null)
  15. {
  16. if (!$key) return $this->data;
  17. return Arr::get($this->data, $key, $default);
  18. }
  19. public function forget($keys)
  20. {
  21. Arr::forget($this->data, $keys);
  22. return $this;
  23. }
  24. }

3.声明facade

  1. namespace App\Helpers\ToJs\Facades;
  2. use Illuminate\Support\Facades\Facade;
  3. class ToJsFacade extends Facade
  4. {
  5. /**
  6. * Get the registered name of the component.
  7. *
  8. * @return string
  9. */
  10. protected static function getFacadeAccessor()
  11. {
  12. return 'tojs';
  13. }
  14. }

4.在config数组添加serviceProvider

providers 添加
\App\Providers\ToJsServiceProvider::class

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

5.为了方便调用可以在写一个helper方法

  1. if (!function_exists('to_js')) {
  2. /**
  3. * Access the javascript helper.
  4. */
  5. function to_js($key = null, $default = null)
  6. {
  7. if (is_null($key)) {
  8. return app('tojs');
  9. }
  10. if (is_array($key)) {
  11. return app('tojs')->put($key);
  12. }
  13. return app('tojs')->get($key, $default);
  14. }
  15. }

在PHP代码需要的地方调用 to_js(['username'=>'test']);

blade模板直接通过 @tojs 就可以在页面渲染出
<script> window.Laravel = {"username":"test"}</script>

以上就是关于laravel自定义模板指令-tojs的详细内容,更多请关注gxlcms其它相关文章!

人气教程排行