我正在尝试定义一个JS变量,该变量从一个聪明的变量中获取其值。
这是我在我的PHP控制器中所做的:
public function hookDisplayBackOfficeHeader()
{
$this->context->controller->addJS($this->_path.'js/bo_setup.js', 'all');
}
我在一个单独的函数上声明变量:
private function _loadTestInfo()
{
$this->context->smarty->assign(array(
'test_username' => 'myuser',
));
}
并从 getContent() 函数调用它:
{
$output = '';
....
$this->output .= $this->display(__FILE__, '/views/templates/admin/back_office.tpl');
$this->_loadTestInfo();
$this->output .= $this->renderForm();
return $this->output;
}
我的bo_setup.js函数如下所示:
var test_username = "{$test_username}";
document.getElementById('username').value = test_username;
但是,运行页面会为"用户名"变量提供"{$test_username}"的值,而不是"myuser"值。
有什么线索吗?
要访问 JavaScript 中的变量,您可以在控制器中分配它们:
Media::addJsDef(array('mymodule' => array('test_username' => 'Your name')));
$this->context->controller->addJS($this->_path.'myscript.js')
然后,您可以在 JavaScript 中或通过控制台使用它们:
let var1 = mymodule.test_username;
可能已经很晚了,但以下内容应该对您有所帮助:
{addJsDef test_username=$test_username|escape:'html':'UTF-8'}
这将添加到 smarty .tpl 文件中,它将为您定义变量。
在此之后,最好确保在加载内容后执行javascript,例如使用document.onload = function ...
。