When using the PHP framework (this article uses ThinkPHP as an example) for page development, we often encounter When it is necessary to substitute the template variables in the controller method into the page JS for operation, the common method is:
let admin={:json_encode($admin)}, //$admin是php数组 level={$level}; console.log(admin, level);
This method can indeed get the value, but there are a few problems
- The syntax of template variables is placed in js, and the editor will report a syntax error
- When the editor's automatic formatting function is used, the declaration structure of the template variables will be destroyed, thus affecting the The use of the automatic formatting code function
- is not beautiful enough
In practice, the more recommended way is:Save template variables to specific nodes, and then use global methods Convert them into global variables. Finally, you need to use the methods of these variables to read these global variables. Take a complete template as an example below:
<!DOCTYPE html> <html lang ="en"> <head> <meta charset="UTF-8"> <title>PHP框架中JS优雅获取模板变量的方式</title> <style> /* 通用的模板数据存放标签,视觉不可见 */ .data-box { display: none; } </style> </head> <body> <!-- 页面内容 --> <h2>Hi,结果请看console</h2> <!-- 数据存储节点,可以同时存在多个data属性 --> <!-- 如果模板变量是数组,须先转成json字符串(如$admin) --> <div class="data-box" data-admin='{:json_encode($admin)}' data-level='{$level}'></div> <script> /* 获取数据的操作 */ /* 初始化页面渲染时传过来的js变量 */ let dataContainerElem = document.querySelector('.data-box'), data = dataContainerElem ? dataContainerElem.dataset : {}, dataBox = {}; //模板变量容器,`.data-box`类选择器所在的所有`data`属性值集合 Object.keys(data).forEach(function (key) { dataBox[key] = data[key]; if (isJsonString(data[key])) dataBox[key] = JSON.parse(data[key]); //是json格式的字串才转对象 }); /** * 判断字串是否属于json字串 */ function isJsonString(str) { let flag = false; if (typeof str != 'string') return flag; try { JSON.parse(str); flag = true; } catch (e) {} return flag; } </script> <script> /* 使用数据 */ //所有保存到数据节点的变量都成为`dataBox`对象的属性 console.log(dataBox.admin, dataBox.level); </script> </body> </html>
In actual development, I will place the css here and the js operation for obtaining data in the global mother template, and then the specific sub-templates only need to inherit the mother template You can use this function to facilitate code reuse.
Recommended: "The latest 10 thinkphp video tutorials"