Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing string with apostrophe to helper method doesn't display correctly

I'm using a helper method from the rails tutorial which concatenates two strings together for use in the title selector in the view. It works perfectly fine, unless there is an apostrophe in the string.

When :group_name contains an apostrophe it comes out like this:

<title>The website | O&amp;#x27;Malley Brothers</title>

Here is the method: app/helpers/application_helper.rb

module ApplicationHelper

  def full_title(page_title)
    base_title = "Chicago Improv Festival"
    if page_title.empty?
      base_title
    else
      "#{base_title} | #{page_title}"
    end
  end
end

Here is how it's used in the layout view. app/views/layouts/application.html.erb:

<title><%= full_title(yield(:title)) %></title>

Here is where the :title is set in another view file: app/views/submissions/show.html.erb

<% provide(:title, @submission.group_name) %>
like image 552
Kevin K Avatar asked Dec 09 '25 15:12

Kevin K


2 Answers

You need to add .html_safe so the apostrophe isn't escaped.

"#{base_title} | #{page_title}".html_safe
like image 155
flynfish Avatar answered Dec 12 '25 13:12

flynfish


It's a bad idea to call .html_safe willy nilly. Unless you have full control over base_title and page_title then you're opening yourself up to an attack, though I'm not sure what kind of attacks can exploit the <title></title> tag.

I had the same problem. The solution was not to use string interpolation, instead:

base_title + ' | ' + page_title
like image 28
Brendon Muir Avatar answered Dec 12 '25 12:12

Brendon Muir



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!