简体   繁体   中英

Rails: Split and wrap each character in a string?

I have something like:

<%= @votes %>

With just outputs a string like:

123

Is there a simple way to wrap each character with some html with a helper?

<span class="outerclass">
  <span class="innerclass">
  1
  </span>
</span>

<span class="outerclass">
  <span class="innerclass">
  2
  </span>
</span>

<span class="outerclass">
  <span class="innerclass">
  3
  </span>
</span>

You could create a helper similar to this:

def wrap_each_char(string, &block)
  string.each_char.map(&block).join
end

Then use it like this (erb):

<%- @votes = "123" -%>
<%- wrap_each_char(@votes) do |c| -%>
  <span class="outer"><span class="inner"><%= c %></span></span>
<%- end -%>

Update: The above example represents one way to pass block level content to a helper, but it's worth noting that this particular example can be simplified by just using the each_char method on the string and avoiding the helper altogether:

<%- @votes.each_char do |c| -%>
  <span class="outer"><span class="inner"><%= c %></span></span>
<%- end -%>

view:

<% @votes.split('').each do |v| %>
  <%= print_vote(v) %>
<% end %>

helper:

def print_vote(vote)
  content_tag(:span, :class => 'outerclass') do
    content_tag(:span, vote, :class => 'innerclass')
  end
end

I'd work toward array'ing the votes before they hit the view, but you're going to have to iterate somewhere and the split doesn't really add much to the implementation anyway. I guess if you really wanted to stuff everything in the helper you could do something like

view:

<%= print_votes(@votes) %>

helper:

def print_votes(votes)
  votes.split('').each do |vote|
    content_tag(:span, :class => 'outerclass') do
      content_tag(:span, vote, :class => 'innerclass')
    end
  end
end

Pretty much the same, it just depends on where you want to put your lines.

# View
<%= char_classes(@votes) %>

# Helper
def char_classes(string)
  string.split.map { |char| '<span class="outerclass"><span class="innerclass">' + char + '</span></span>'}.join
end

You'll probably want to choose more expressive method/var names...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM