Eco template renders integer when using 'end' statement

不羁的心 提交于 2019-12-10 11:55:14

问题


I have a pretty simple Backbone View that I'd like to have render some blocks of HTML conditionally. I'm seeing a behavior where following the conditionally rendered HTML there is a integer rendered as well. From what I can tell, it seems to happen when I use the end statement to terminate a conditional block.

Here's some code that is demonstrating the error for me:

<% if true: %>Hello World!<% end %>

I would expect this to renderHello World! into the containing element. However, it's actually rendering Hello World!2.

If I add several of blocks in the same template:

<% if true: %>Foo, <% end %>
<% if true: %>Bar, <% end %>
<% if true: %>Baz<% end %>

I would expect this to render Foo, Bar, Baz into the containing element. However, it's actually rendering Foo, 2 Bar, 5 Baz8. After running a somewhat larger set of them, it seems the integer being printed goes up by 3 every time. From reading over the gem's README I can't see anything I'm doing wrong.

Any help would be much appreciated!


回答1:


Alternatively you could use the postfix format.

<%= "Hello World!" if true %>



回答2:


I have the same problem. Have you solved it already?

I think it's caused by if statements being wrapped in __obj.push() calls in the compiled JS. For example, in my script, there is a piece of code

<%- if !@blok: %>
  <%- to_html(@create_link('c', @session['course'])) %>
<%- end %>

which gets compiled to

[1] __out.push(!this.blok ?
[2]  (__out.push('\n '),
[3]   __out.push(to_html(this.create_link('c', this.session['course']))),
[4]   __out.push('\n ')
[5]  ) : void 0)

If I understand it correctly, it means that it will first push the \n, the result of the function, another \n to the output. But the last push (line 4) will return number of the elements in the array, which will be in turn pushed to the array itself by the outer push (line 1).

I've tried to change the Array.prototype.push to return something else, but it seems that messes things even more (since it's a core function).



来源:https://stackoverflow.com/questions/10035900/eco-template-renders-integer-when-using-end-statement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!