AllieCat
AllieCat

Reputation: 3960

Truncate string in Rails: "..." showing up on strings at length

I'm currently trying to truncate any strings greater than 65 characters.

My code is

<title><%= truncate(title.html_safe, length:65) %></title>

It works great for titles longer than 65 characters. But titles that are exactly 65 character still get truncated.

For example:

title:"This post is exactly 65 characters characters characters characte"

shows on page as "This post is exactly 65 characters characters characters chara..."

Should I not be using truncate?

Upvotes: 8

Views: 10991

Answers (5)

Nimish
Nimish

Reputation: 1066

If you are using rails 4.2 or above then you can use truncate_words method.

<title><%= (title.html_safe).truncate_words(5) %></title>

Upvotes: 5

Mandeep
Mandeep

Reputation: 9173

We call it Ellipsis. Just to add to the above answers you can achieve ellipsis by css, jquery and rails.

css:

.truncate {
  width: 250px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

Jquery:

There is a really good jquery plugin dotdotdot. I have used it one of my projects and it works like a charm. It uses height and width of your parent element smartly to show ellipsis.

Rails:

Rails has a text helper truncate which can be used like:

<%= truncate("Once upon a time in a world far far away", length: 65) %>

CSS is obviously the quickest way to achieve ellipsis but it has its disadvantages that it doesn't provide a way to limit your characters and it's tricky to get it to work for multiple lines.

Jquery plugin dotdotdot works great for multiple lines but i don't think it has option to specify character limit either.

Rails truncate it obviously server side and will allow you an option to specify character limit.

Upvotes: 1

Nithin
Nithin

Reputation: 3699

title = "This post is exactly 56 characters characters characters characte".length => 65

<title><%= truncate(title.html_safe, length:56) %></title> # will be truncated

<title><%= truncate(title.html_safe, length:65) %></title> # this should work fine, I just tried.

Rails 3.2.17

Upvotes: 2

nickcen
nickcen

Reputation: 1692

the truncate method work just as expected. Please output the length after your invocation of title.html_safe, is it possible that your string contains some trailing spaces?

Upvotes: 1

pdobb
pdobb

Reputation: 18037

truncate is the right method. This might be a bug in your version of rails? Here's what I get on my console:

[5] pry(main)> helper.truncate("This post is exactly 56 characters characters characters characte", length: 65)
=> "This post is exactly 56 characters characters characters characte"
[6] pry(main)> helper.truncate("This post is exactly 56 characters characters characters characte", length: 64)
=> "This post is exactly 56 characters characters characters char..."

I'm running Rails 4.0.4 in this example.

Upvotes: 7

Related Questions