布尔检查下划线模板 [英] Boolean checks in underscore templates
问题描述
我必须更换默认的下划线teplating delimiters / Interpolate正则表达式以兼容asp.net webforms。从网站我选择了胡须,如语法
I had to replace the default underscore teplating delimiters/Interpolate regex for compatibility with asp.net webforms.From the website i opted for mustache like syntax
_.templateSettings = {
interpolate : /\{\{(.+?)\}\}/g
};
试过这个
_.template({{if(loggedIn)Welcome {{name}}}},{name:James,completed:true});
但似乎这不是使用模板系统检查布尔表达式的方式(因为发生错误)。但是从文档似乎可能
but seems this is not the way( since a error occurred) to check boolean expression using a templating system. But from the docs seems it is possible
以及执行任意JavaScript代码,<%...%>
as well as execute arbitrary JavaScript code, with <% … %>
- 那么如何使用上面提到的插值执行任意js代码
- 插值适用于
<%= ...%>
。 - 转义适用于
<% - ...%>
。 - 评估适用于
<%...%>
。 - interpolate is for
<%= ... %>
. - escape is for
<%- ... %>
. - evaluate is for
<% ... %>
.
推荐答案
您的问题是您要为定义一个Moustache风格的替代品<%= ...%> ;
但尝试在通常使用<%...%>
的地方使用它。来自精细手册:
Your problem is that you're defining a Mustache-style replacement for <%= ... %>
but trying to use it where you'd normally use <% ... %>
. From the fine manual:
定义一个 interpolate 正则表达式来匹配应该逐字插入的表达式,一个转义正则表达式来匹配应该在HTML转义后插入的表达式,以及一个评估正则表达式以匹配应该在不插入结果字符串的情况下进行评估的表达式。
Define an interpolate regex to match expressions that should be interpolated verbatim, an escape regex to match expressions that should be inserted after being HTML escaped, and an evaluate regex to match expressions that should be evaluated without insertion into the resulting string.
因此有三个正则表达式play:
So there are three regexes in play:
您告诉Underscore使用 {{...}}
代替<%= ...%>
然后您收到错误,因为 if(loggedIn)
可以T插值。您只需要修复 _。templateSettings
以反映您要执行的操作:
You're telling Underscore to use {{ ... }}
in place of <%= ... %>
and then you're getting an error because if(loggedIn)
can't be interpolated. You just need to fix your _.templateSettings
to reflect what you're trying to do:
_.templateSettings = {
evaluate: /\{\{(.+?)\}\}/g,
interpolate: /\{\{=(.+?)\}\}/g
};
然后你的模板看起来像这样:
and then your template would look like this:
{{ if(loggedIn) { }}Welcome {{= name }} {{ } }}
演示: http://jsfiddle.net/ambiguous / RwgVg / 8 /
您需要包含 {
和<$ c $模板中的c>} ,因为 _。template
在编译模板时添加分号,结果如下:
You'll need to include the {
and }
in the template because _.template
adds semicolons when compiling the template, that results in things like:
if(loggedIn) {; ...
(感谢 JaredMcAteer 指出这一点。)
您可能还想添加一个转义正则表达式,可能是 / \ {\ { - (。+?)\} \} / g
。
You might want to add an escape regex as well, that would probably be /\{\{-(.+?)\}\}/g
.
这篇关于布尔检查下划线模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!