【问题标题】:How should we combine the div with link_to in Rails?我们应该如何在 Rails 中将 div 与 link_to 结合起来?
【发布时间】:2023-03-10 01:12:01
【问题描述】:

我的初衷是在图片上显示一些文字。同时,当我们点击图片时,网页会被重定向。 我将 link_to 函数与包含背景图像的 div 一起使用。 代码是这样的:

 <%= link_to raw('<div style="background-image:url(<%= image_url  '1.jpg'%>);width:340px;"> This is a  test</div>'),index_by_dvp_domain_path %>

但是系统告诉我有 SyntaxError。

【问题讨论】:

    标签: ruby-on-rails html link-to


    【解决方案1】:

    您可以将 link_ 传递给包含您要显示的内容的块。因此,您可以使用link_to(url, option={}, &amp;block) 而不是使用link_to(display, url, options={})

    <%= link_to index_by_dvp_domain_path do %>
      <div style="background-image: url(<%= image_url '1.jpg'%>);width:340px;"> 
       This is a  test
      </div>
    <% end %>
    

    完成此操作后,您可以将其视为普通 html。

    与往常一样,我建议尝试将任何样式移到它自己的单独样式表中。

    【讨论】:

      【解决方案2】:

      以下是最好的方法

      <%= link_to index_by_dvp_domain_path do
            content_tag(:div, 'This is a  test',:style=>"background-image:url(#{image_url}  '1.jpg');width:340px;" )
          end
      %>
      

      <%= link_to content_tag(:div, 'This is a  test',:style=>"background-image:url(#{image_url}  '1.jpg');width:340px;" ), index_by_dvp_domain_path  %>
      

      【讨论】:

        【解决方案3】:

        请试一试

        <%= link_to raw('<div style="background-image:url(#{image_url  '1.jpg'}%>);width:340px;"> This is a  test</div>'),index_by_dvp_domain_path %>
        

        【讨论】:

          【解决方案4】:

          我认为即使你有一个包含多个标签的大块,使用下面的 Link_to 会更简单:

          <%= link_to desired_path do %>
              <div class="linkable">
                  <another div>
                       ... some other tags
                  </another div>
              </div>
          <% end %>
          

          我建议您为鼠标悬停事件使用不同的背景颜色,因为它向查看者显示它是一个链接!

          在你的 .css 文件中:

          .linkable:hover{
              background-color: red;
          }
          

          【讨论】:

            【解决方案5】:

            我很惊讶没有人想出在 Rails 中执行此操作的常规方法。

            <%= link_to image_tag("/images/1.jpg",:size => "340X340"),index_by_dvp_domain_path %>
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2022-11-02
              • 1970-01-01
              • 2011-01-02
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多