2
votes

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.

1
String.slice(post.content, 0..50), please check this answer - stackoverflow.com/a/39395092/3102718 - Alex Avoiants
There is also a package that offers a truncate function and more: github.com/ikeikeikeike/phoenix_html_simplified_helpers - Joe Eifert

1 Answers

10
votes
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