在Marionette/下划线模板中将属性与奇怪的字符一起使用 [英] Use attributes with weird chars in Marionette / underscore template
问题描述
我有一个模型,其属性名称如@id
,@type
等.
I have a model with attributes names like @id
, @type
, etc.
如果我尝试在Marionette.ItemView
模板(带有下划线)中使用<%= @id %>
,我会得到
If I try to use <%= @id %>
in a Marionette.ItemView
template (with Underscore) I get
未捕获到的SyntaxError:意外令牌ILLEGAL
Uncaught SyntaxError: Unexpected token ILLEGAL
使用语法['@id']
不会产生预期的结果.
Using the syntax ['@id']
does not produce the expected result.
我必须重写serializeData
函数吗?
谢谢
推荐答案
下划线模板需要<%= ... %>
内的JavaScript表达式,编译后的模板使用
Underscore templates require JavaScript expressions inside <%= ... %>
, the compiled template uses with
so you can usually reference object properties as though they were variables. Your problem is that @id
is not a valid JavaScript expression.
是的,提供您自己的 serializeData
删除@
可能是您最好的选择.另一种可能性是将variable
选项与 _.template
一起使用:
So yes, providing your own serializeData
to remove the @
s is probably your best bet. Another possibility would be to use the variable
option with _.template
:
默认情况下,模板通过
with
语句将数据中的值放置在本地范围内.但是,您可以使用变量设置指定一个变量名.这样可以大大提高模板的渲染速度.
By default, template places the values from your data in the local scope via the
with
statement. However, you can specify a single variable name with the variable setting. This can significantly improve the speed at which a template is able to render.
_.template("Using 'with': <%= data.answer %>", {answer: 'no'}, {variable: 'data'});
=> "Using 'with': no"
然后您可以使用<%= data['@id'] %>
之类的东西;问题在于,与仅使用自定义serializeData
方法清理@
相比,使这种方法与Marionette结合使用可能会做更多的工作.
Then you could use things like <%= data['@id'] %>
; the problem is that getting this approach to work with Marionette might be more work than simply cleaning up the @
s in a custom serializeData
method.
这篇关于在Marionette/下划线模板中将属性与奇怪的字符一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!