How does one comment in an erb template?

2019-06-15 14:52发布

I have some trivial markup that looks like the following:

<li class="someclass">
  <=% t'model.attr' %>
</li>

Is there a trivial way to comment that out? Just wrapping <!-- --> around the block will still leave the ruby code available to the template. This means I have to comment out the HTML and Ruby specific code separately.

What's the best way to comment out all three lines with the least amount of markup?

4条回答
爷的心禁止访问
2楼-- · 2019-06-15 14:57

You can comment ERB blocks using #:

<!-- <li class="someclass"> -->
  <%#= t'model.attr' %>
<!-- </li> -->

or avoid the literal HTML using Rails content_tag method:

<%#= content_tag :li, t'model.attr', :class=>:someclass %>
查看更多
倾城 Initia
3楼-- · 2019-06-15 14:58

Doesn't work:

<%# <li class="someclass">
  <=% t'model.attr' %>
</li> %>

Does work:

<% if false %>
<li class="someclass">
  <=% t'model.attr' %>
</li>    
<% end %>
查看更多
孤傲高冷的网名
4楼-- · 2019-06-15 15:09

=begin and =end are the Ruby version of block comments.

Using them in an erb template:

<%
=begin
%>
<li class="someclass">
  <=% t'model.attr' %>
</li>
<%
=end
%>
查看更多
女痞
5楼-- · 2019-06-15 15:24

Edited because I noticed the true intention of your question:

<%
=begin
%>
<li class="someclass">
  <%= t'model.attr' %>
</li>
<%
=end
%>

In every syntax highlighter that I've used (mainly textmate), this needs to be at the very beginning of the line, you can't indent it for it to appear commented. I don't know if that's a rule or a poor implementation of the highlighting.

查看更多
登录 后发表回答