Skip to content
鼓励作者:欢迎打赏犒劳

js-template

Handlebars

官网:https://handlebarsjs.com/zh/

很简单,很强大,很好用,文档很详细

html
 "handlebars": "^4.7.8",
vue
<script setup>
    import Handlebars from 'handlebars'
    let str = `<ul class="people_list">
  {{#each people}}
    <li>{{this}}</li>
  {{/each}}
</ul>`
    let template = Handlebars.compile(str);
    let generateCode = template({
      people: [
        "Yehuda Katz",
        "Alan Johnson",
        "Charles Jolley",
      ]
    });
    console.log(generateCode)
</script>

特殊符号问题解决

方案 1:使用 \ 转义符号(适合少量特殊字符)

在需要保留的 {{ 或 }} 前添加反斜杠 \ 进行转义:

vue
 \{{ (page.index - 1) * page.size + scope.$index + 1 }}  <!-- 转义此处 -->

方案 2:使用 {{{raw}}} 原始内容块(适合大量特殊字符)

通过 Handlebars 的 raw Helper 包裹整段原始内容,避免解析内部的特殊符号:

注册 raw Helper(在代码生成前执行一次):

html
Handlebars.registerHelper('raw', function(options) {
  return options.fn();
});

在模板中使用 {{{raw}}} 包裹原始内容:

vue
<template>
  {{{{raw}}}}
     {{ (page.index - 1) * page.size + scope.$index + 1 }}
  {{{{/raw}}}}
</template>

方案3:自定义函数

html
Handlebars.registerHelper('braces', function() {
    return '{';
});

使用: user_id = #{userId}

html
user_id = #{{ braces }} userId {{ rbrace }}

快速测试

js
import Handlebars from 'handlebars'
import fs from 'fs/promises'; 

// 读取模板文件
const loadTemplate = async (path) => {
    const data = await fs.readFile(path, 'utf-8');
    return data;
};
let data = await loadTemplate('E:\\ws\\demo\\List.txt');
let template = Handlebars.compile(data);
let generateCode = template({
    "name":"www"
});
console.log(generateCode)

如有转载或 CV 的请标注本站原文地址