我正在使用 backbone 的下划线模板引擎和 mustache 格式模式。
我已经在项目的其他地方成功地使用了它,但现在我第一次使用 mustache 的循环列表模式来填充模板,该模板引发了一个让我有点困惑的错误。 chrome 中的错误是:
"Uncaught SyntaxError: Unexpected token ILLEGAL"
并在回溯中指向下划线的模板函数,这是非常无用的,但在 firebug 中我得到了一个更有用的错误,如下所示:
表明哈希符号“#”是问题所在,这是有道理的,因为我知道 mustache 工作正常,因为项目的许多其他部分都在很好地使用它,这也是我第一次使用我的模板中的哈希符号。它看起来像是循环功能或下划线的插值/模板设置的问题。
这是我的模板的相关部分:
<div class="thumblist thumblistleft" id="currentprojectslist">
<div class="thumb-list-header">
<h2>current projects</h2>
</div>
<div class="thumb-list-area">
<ol>
{{#worklist}} <!----- LOOK HERE --->
{{#current}}
<li><a>{{title}}</a></li>
{{/current}}
{{/worklist}}
</ol>
</div>
</div>
这是一个 JSON 示例(所有验证都很好)
{blah blah blah lot in here before,"worklist":[{"thumb":"img/project-s.jpg","id":"340","title":"Test Project One","desc":"big load of content here","current":true}], and so on....}
我最初在此处遵循此示例以供引用: http://mustache.github.com/#demo
现在我认为问题可能出在这里:
underscore.js 建议在渲染 mustache 模板之前使用它:
_.templateSettings = {
evaluate : /\{\[([\s\S]+?)\]\}/g,
interpolate : /\{\{([\s\S]+?)\}\}/g
};
还有:
interpolate : /\{\{(.+?)\}\}/g
还有插值语句,我都试过了。但是我的正则表达式知识真的很差,我觉得它可能无法容纳哈希?无论如何……我完全被难住了。 有人可以帮我吗?
甚至可以这样循环吗?查看下划线来源我不确定: http://documentcloud.github.com/underscore/docs/underscore.html#section-120
非常感谢
最佳答案
今天遇到了这个问题。问题似乎是 Underscore 执行模板的顺序:转义、插值,然后求值。因此,您需要在插值正则表达式中显式忽略 {{#
的任何匹配项:
_.templateSettings = {
evaluate: /\{\{#([\s\S]+?)\}\}/g, // {{# console.log("blah") }}
interpolate: /\{\{[^#\{]([\s\S]+?)[^\}]\}\}/g, // {{ title }}
escape: /\{\{\{([\s\S]+?)\}\}\}/g, // {{{ title }}}
}
它实际上与 Mustache 的工作方式不同:Underscore 的模板中没有合适的 block ,因此不需要结束 block {{/}}
。您只需像使用标准 Underscore 模板一样匹配您的语句。
关于javascript - mustache 格式的 Backbone /下划线模板导致#磅/哈希符号出错?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9002203/