Rails通过'read more'切换截断 [英] Rails truncate with a 'read more' toggle

查看:86
本文介绍了Rails通过'read more'切换截断的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一段我想要截断的段落,可以点击阅读更多,然后将其与其他内容一起滑开。内容来自数据库字段。以下是截断的内容:

I have a paragraph that I want truncated with the option of clicking "read more" and have it slide open with the rest of the content. The content is coming from a database field. Here's what I have for the truncate:

<%= truncate(@major.glance, :length => 250, :omission => '... Read More')%>

我似乎找不到从数据库中提取数据的方法。我看到很多使用全文的示例,以及要隐藏在单独div标签中的文本。但是,由于此内容来自数据库并且是动态的,因此无法找到有关如何执行此操作的任何信息。

I can't seem to find a way to do this with data pulled from a database. I see a lot of examples using the full text with the text you want to hide in a separate div tag. But, since this content is coming from a database and is dynamic I can't find any information on how to do it.

推荐答案

您可以尝试以下

<div>
  <% if @major.glance.length > 250 %>
    <%= link_to_function truncate(@major.glance, length: 250), "$(this).parent().html('#{escape_javascript @major.glance}')" %>
  <% else %>
    <%= @major.glance %>
  <% end %>
</div>

或者如果您更喜欢使用了解更多 link

or if you prefer to use the Read more link

<div>
  <% if @major.glance.length > 250 %>
    <%= truncate(@major.glance, length: 250) %>
    <%= link_to_function '...Read more', "$(this).parent().html('#{escape_javascript @major.glance}')" %>
  <% else %>
    <%= @major.glance %>
  <% end %>
<div>

更新

因为在Rails 4中, link_to_function 已被弃用,建议使用非阻碍js,请使用以下

Since in Rails 4, link_to_function is deprecated and it is advisable to have non obstrusive js, use the following

<div>
  <% if @major.glance.length > 250 %>
    <%= truncate(@major.glance, length: 250) %>
    <%= link_to '...Read more', '', class: "read-more-#{@major.id}" %>
    <script>
      $('.read-more-<%= @major.id %>').on('click', function(e) {
        e.preventDefault()
        $(this).parent().html('<%= escape_javascript @major.glance %>')
      })
    </script>
  <% else %>
    <%= @major.glance %>
  <% end %>
<div>

这篇关于Rails通过'read more'切换截断的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆