Javascript 如何从模板中提取把手列表?
给定一个带有有效句柄的字符串,比如Javascript 如何从模板中提取把手列表?,javascript,handlebars.js,Javascript,Handlebars.js,给定一个带有有效句柄的字符串,比如“handlebar{{{doesWhat}}”,我知道我可以使用handlebar.compile编译它,这样我就可以用以下代码向doesWhat注入一个变量: const template=handlebar.compile(“handlebar{{{doesWhat}”); const rendered=template({doesWhat:“rocks!”}); //返回“把手石头!” 我想知道是否有办法提取库编译时检测到的所有把手列表(不包括注释、助
“handlebar{{{doesWhat}}”
,我知道我可以使用handlebar.compile
编译它,这样我就可以用以下代码向doesWhat
注入一个变量:
const template=handlebar.compile(“handlebar{{{doesWhat}”);
const rendered=template({doesWhat:“rocks!”});
//返回“把手石头!”
我想知道是否有办法提取库编译时检测到的所有把手列表(不包括注释、助手或“语言”的其他功能)?会有回报的东西:
['doesWhat']
一种简单的方法是在字符串上使用regex
let result=“把手{{{doesWhat}}{{{example}}”。匹配(/{{{[{]?(.*?[}]?}}/g)
console.log(result)
您应该匹配“{{{”
和“}}}”
中的任何内容。这并不能解释诸如循环和中继器之类的事情
我添加了“向后看”和“向前看”检查。请记住,旧版本的JavaScript不支持负面外观落后
handlebar.registerHelper('loud',str=>str.toUpperCase())
常量表达式模式=/(?format.match(表达式模式)
让format='{{name}}{{loud does}}}我的{{thing.value}}!'
让选项={name:'handlebar',does:'rocks',thing:{value:'socks'}
让template=handlebar.compile(格式)
console.log(提取表达式(模板))
document.querySelector(“#rendered”).innerHTML=模板(选项)
这将适用于这些基本模板,但一旦我们使用注释、钩子或助手,它将无法正常工作,尽管它实际上比其他解决方案更强大,但没有给出把手列表:我希望使用loud does
接收does
,并排除注释-这是正确的由于我没有使用太多的助手,所以只需稍加调整即可满足我的需要