You can easy to pass CakePHP4 variables to JS in View.
- PHP >= 7.0
- CakePHP >= 4.0
In Application.php
<?php
$this->addPlugin('Pack');
In controller.
<?php
class AppController extends Controller
{
public function initialize()
{
$this->loadComponent('Pack.Pack');
}
...
}
In layout php or template php.
<?= $this->Pack->render();?>
Just set variables in your controller.
<?php
$entity = $this->Hoge->get($id);
$array = [...];
$this->Pack->set('entity', $entity);
$this->Pack->set('array', $array);
## OR ##
$this->Pack->set(compact('entity', 'array'));
Just get the variables in your JS in view.
Pack.entity;
Pack.array;
- set($varName, $variable) … Set variable in Pack.
- remove($varNamee) … Remove variable in Pack.
- show() … Show all variable in Pack.
- rename($namespace) … Change Pack's namespace in JS.
example
In controller
$this->Pack->rename('Hoge');
$this->Pack->set('array', $array);
In js
Hoge.array;