Domanda

In my Rails app, I was having issues with rendering a link_to because, for some reason, a new line is added through my link_to. For example, when I try to create the link with:

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

I would get this in the console:

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

Which would lead to this error:

Uncaught SyntaxError: Unexpected token ILLEGAL

I tried using the method "squish" to get rid of the newline:

<% 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>

But when I try to incorporate the "squished" variable on my page, it doesn't get rendered as link:

enter image description here

How can I render the code correctly as a link while removing the new line?

Here is my partial 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 %>
È stato utile?

Soluzione 2

I ended up using sanitize to remove new lines:

<% 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>

Altri suggerimenti

Try adding a dash at the end of the ERB tags where you don't want an empty line to be added. Like this -%>

<% 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 -%>
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top