来自link_to的换行问题

时间:2014-01-07 05:43:39

标签: ruby-on-rails link-to

在我的Rails应用程序中,我遇到了渲染link_to的问题,因为由于某种原因,我的link_to添加了一个新行。例如,当我尝试使用:

创建链接时
<% byline = render :partial => "projects/author_byline", :locals => {:project => image.project, :source=>"home"} %>
<script type="text/javascript">
    console.log('byline : <%= byline %>');
</script>

我会在控制台中得到这个:

console.log('byline :   <a href="/users/scientiffic" class="author_link">scientiffic</a>
');

哪会导致此错误:

未捕获的SyntaxError:意外的标记ILLEGAL

我尝试使用“squish”方法摆脱换行符:

<% byline = render :partial => "projects/author_byline", :locals => {:project => image.project, :source=>"home"} %>
<script>
 $('.carousel-inner.featureSlides').append('<%=link_to image.project.title, project_path(image.project) %> by <%= byline.squish %>')
</script>

但是当我尝试在页面上加入“压扁”变量时,它不会呈现为链接:

enter image description here

如何在删除新行时正确地将代码呈现为链接?

这是我的部分author_byline:

<% num_users = project.users.count %>
<% project.users.order("username ASC").each_with_index do |user, index| %>
    <% if num_users > 2 && index == num_users-1 %> , and <% end %><%= link_to user.username, user_path(user), :class=> "author_link" %><% if num_users == 2 && index == 0 %> & <% elsif num_users > 2 && index != num_users-2 && index != num_users-1 %> , <% end %>
<% end %>

2 个答案:

答案 0 :(得分:0)

尝试在ERB标记的末尾添加短划线,您不希望在其中添加空行。像这样-%>

<% num_users = project.users.count -%>
<% project.users.order("username ASC").each_with_index do |user, index| -%>
    <% if num_users > 2 && index == num_users-1 %> , and <% end %><%= link_to user.username, user_path(user), :class=> "author_link" %><% if num_users == 2 && index == 0 %> & <% elsif num_users > 2 && index != num_users-2 && index != num_users-1 %> , <% end %>
<% end -%>

答案 1 :(得分:0)

我最终使用sanitize删除了新行:

<% byline = render :partial => "projects/author_byline", :locals => {:project => image.project, :source=>"home"} %>

<script>
    $('.carousel-inner.featureSlides').append('..by <%= sanitize(byline.gsub(/(?:\n\r?|\r\n?)/, "")) %>');
</script>