【发布时间】:2014-10-15 08:24:28
【问题描述】:
我有一个测试文件“templates.txt”,我正在通过 ajax 调用加载它。
文本文件的内容就是这种格式。
{template templateA}
templateA content
{/template}
{template templateB}
templateB content
{/template}
{template templateC}
templateC content
{/template}
当我通过 ajax 加载它时,我将整个文件的内容作为字符串获取。 假设我在变量 templateContent 中有文件的内容。
var templateContent = myFileContent;
但是我想解析这个字符串变量,并将其转换为对象,如下所示。
{
templateA : templateA content,
templateB : templateB content,
templateC : templateC content
}
如何在 javascript 中做到这一点?正则表达式可以是一个不错的选择吗?
注意:此格式有要求。甚至 Google Closure 模板也使用相同的格式。 https://developers.google.com/closure/templates/docs/helloworld_js
【问题讨论】:
-
为什么不构建 JSON 格式的文件内容?
-
你的模板文件是那种奇怪的格式吗?你不能把它格式化成 JSON 格式吗?
-
@Moob 格式并不奇怪。有一个要求。甚至 google 闭包模板也使用相同的格式。查看链接developers.google.com/closure/templates/docs/helloworld_js
-
@hindmost 请检查已编辑的问题。
标签: javascript jquery regex