在 Rails 中构建看起来不错的外部 URL



>我正在用这个视图渲染一个外部链接:

<%= link_to public_web(company), class:" text-sm text-decoration-none", :target => "_blank" do %>
<i class="fa fa-globe mr-3"></i>
<span class="text-muted"><%=  "#{public_web(company)}" %></span>
<% end %>

和以下帮助程序

def public_web(company)
URI::HTTPS.build({:host => company.marketings.first.try(:website)}).to_s 
end

但是 url 长度破坏了 UI 设计(我想控制最大长度(

如何截断它?

溶液:

我修改了助手,如下所示:

def public_web(company)
response = URI::HTTPS.build({:host => company.marketings.first.try(:website)}).to_s
truncate(response, length: 25, omission: '...')
end

如果您只是想截断链接的文本,那么这是一种方式

<%= link_to public_web(company).truncate(20), class:" text-sm text-decoration-none", :target => "_blank" do %>
<i class="fa fa-globe mr-3"></i>
<span class="text-muted"><%= public_web(company) %></span>
<% end %>

阅读更多关于 Rails 中truncate方法的信息

最新更新