如何在 CakePHP 3.0 中将控制器数据传递给 JS 文件

How to Pass the Controller Data to JS File in CakePHP 3.0

在 CakePHP 2.0 中,我使用下面的 link 将控制器数据传递到 js 文件。但是,我不能再使用这个方法了,因为 CakePHP 3.0 已经删除了 js 助手。

除了使用 js 助手和下面的 link 之外,我是否有新技术可以将控制器数据传递到 js 文件或替代方法?

http://www.php-dev-zone.com/2014/01/how-to-pass-controller-data-to-js-file.html

相关代码:

public function beforeRender()
{
    // We are Setting the jsvariables array which holds the
    // variables that will be used in js files.
    $this->set('jsVars', $this->_jsvariables);
}
<?php echo $this->Html->scriptBlock('var jsVars = '.$this->Js->object($jsVars).';'); ?>

只需检查 JsHelper::object() 方法在做什么,然后手动执行。

https://github.com/cakephp/.../2.7.0/lib/Cake/View/Helper/JsBaseEngineHelper.php#L127

基本上只是对json_encode()的调用,所以只需相应地替换辅助方法调用即可:

<?php echo $this->Html->scriptBlock('var jsVars = ' . json_encode($jsVars) . ';'); ?>