Вопрос

How can I get the below helper with ruby code to display the ruby object on screen rather then just outputting the below in the DOM.

def day_nav
  html = ""
  html += '
  <a href="#day1">
    <div class="sixcol dayButton">#{ @event.start_date.strftime("%B %d, %Y") }</div>
  </a>
  <a href="#day2">
    <div class="sixcol last dayButton">#{ @event.end_date.strftime("%B %d, %Y") }</div>
  </a>'
  html.html_safe
end
Это было полезно?

Решение

The reason you're seeing @event.start_date.strftime("%B %d, %Y") in the DOM, straight up, is because your outer level of quotes is a single quote (') and single quotes do not run interpolations of any sort (including #{}). So you could fix your method by using double quotes or any other string literal representation that allows for interpolation... although it's apparent why you didn't want to use double quotes. So instead of double quotes you can use %() as your string literal representation. For example:

def day_nav
  html = ""
  html += %(
  <a href="#day1">
    <div class="sixcol dayButton">#{ @event.start_date.strftime("%B %d, %Y") }</div>
  </a>
  <a href="#day2">
    <div class="sixcol last dayButton">#{ @event.end_date.strftime("%B %d, %Y") }</div>
  </a>)
  html.html_safe
end

That said, this is not at all the ruby way to write a helper method like this. Here's what I'd recommend overall:

def day_nav
  links = [
    link_to("#day1") do
      content_tag(:div, @event.start_date.strftime("%B %d, %Y"), class: "sixcol dayButton")
    end,
    link_to("#day2") do
      content_tag(:div, @event.end_date.strftime("%B %d, %Y"), class: "sixcol last dayButton")
    end
  ]
  safe_join(links, "\n")
end

Другие советы

This would be enough:

<%= @event.start_date.strftime("%B %d, %Y") %>
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top