Reputation: 6415
I have a text field called content that I need to display an excerpt of.
What is the best way to do this?
Something like:
<% post.content.slice(0..50) %>
is what I have in mind; however, this gives me an argument error.
What is the best way to display the first 50 characters of the content text field?
Alternatively - could I create an excerpt field when the data is created/saved into the database?
Any help is appreciated. Thanks in advance.
Upvotes: 2
Views: 1863
Reputation: 15746
defmodule MyApp.StringFormatter do
def truncate(text, opts \\ []) do
max_length = opts[:max_length] || 50
omission = opts[:omission] || "..."
cond do
not String.valid?(text) ->
text
String.length(text) < max_length ->
text
true ->
length_with_omission = max_length - String.length(omission)
"#{String.slice(text, 0, length_with_omission)}#{omission}"
end
end
end
That's what I use in my app, I believe I shamelessly copy pasted it from somewhere but it works just fine and obviously you can modify it to your needs.
But if you dont need this fancy ommision thing then
String.slice(post.content, 0..50)
should work just fine
Upvotes: 10