【问题标题】:How to wrap links into ul li in Ruby?如何在 Ruby 中将链接包装到 ul li 中?
【发布时间】:2021-01-25 22:31:01
【问题描述】:

我为语法文盲道歉,我不必处理 Ruby,但有必要将链接包装在 ul> li 列表中(ul>li>a 而不是 a)

def links_to_hashtags(hashtags = object.hashtags)
  hashtags.map(&:to_s).map do |hashtag|
    # XXX transitional
    url = h.hashtag_page_enabled? && h.logged_out? ? h.tag_path(hashtag.downcase) : h.hashtag_friends_path(q: hashtag.downcase)
    h.link_to "##{hashtag}", url, dir: h.html_dir(hashtag)
  end.join(' ').html_safe
end

我尝试过这种方式,但它有一些语法错误:

def links_to_hashtags(hashtags = object.hashtags)
  hashtags.map(&:to_s).map do |hashtag|
    # XXX transitional
    url = h.hashtag_page_enabled? && h.logged_out? ? h.tag_path(hashtag.downcase) : h.hashtag_friends_path(q: hashtag.downcase)
    h.content_tag :ul, class: 'fancy' do
    h.concat h.content_tag :li,
    h.link_to "##{hashtag}", url, dir: h.html_dir(hashtag)
  end.join(' ').html_safe
end   

非常感谢您的回复!

【问题讨论】:

    标签: ruby-on-rails ruby helper


    【解决方案1】:
    def links_to_hashtags(hashtags = object.hashtags)
      h.content_tag :ul, class: 'fancy' do
        hashtags.map(&:to_s).each do |hashtag|
          concat h.content_tag :li do
            concat link_to_hashtag(hashtag)
          end
        end
      end  
    end
    
    def link_to_hashtag(hashtag)
      # prefer if ... else over unreadably long ternary expressions
      url = if h.hashtag_page_enabled? && h.logged_out? 
        h.tag_path(hashtag.downcase) 
      else 
        h.hashtag_friends_path(q: hashtag.downcase) 
      end
      h.link_to ['#', hashtag].join, url, dir: h.html_dir(hashtag)
    end
    

    content_tag 这样的每个内容助手都会创建自己的字符串缓冲区。当您在块中使用 concat 时,您正在写入该标记的缓冲区 - 就像您在 ERB 中使用 <%= 时一样。这消除了进行笨拙的字符串连接和处理被转义的 html 标签的需要。

    然而,这确实是您应该考虑使用 a partial 代替的东西。

    <ul class="fancy">
      <% hashtags.each do |hashtag| %>
        <li><%= link_to_hashtag(hashtag) %></li>
      <% end %>
    </ul>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-05-21
      • 2014-07-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-20
      • 2013-07-27
      • 1970-01-01
      相关资源
      最近更新 更多