Truncate words/chars in Phoenix?

Hi, another question from me (please bear with me…)

How I can truncate words or chars on phoenix? I only found this doc, but Err… It doesn’t help that much :sweat:

I tried this : <%= truncate(idea.content) %>, but not working.

While I expecting something like this, so n00bs like me can understand better :grinning:

Thank you in advance for any help you can provide :slight_smile:
Cheers!

The default truncation point in truncate/2 is 30 characters so perhaps the string you are passing is shorter than that?

Looking at the source code there are two options that determine behaviour, used like:

truncate(idea.content, length: 13, omission: "...")

Hi @kip
Thank you for fast response :smiley:

it’s still compilation error

Compiling 1 file (.ex)

== Compilation error on file web/views/idea_view.ex ==
** (CompileError) web/templates/idea/index.html.eex:13: undefined function truncate/2
    (stdlib) lists.erl:1338: :lists.foreach/2
    (stdlib) erl_eval.erl:670: :erl_eval.do_apply/6
    (elixir) lib/kernel/parallel_compiler.ex:117: anonymous fn/4 in Kernel.ParallelCompiler.spawn_compilers/1

Also, what omission is?

Thanks!

Did you install phoenix_html_simplified_helpers?

1 Like

Mm… Not yet…
So this is 3rd party? I thought something like this is already built-in :confused:

I’ll try to install it

Thank you!

Ok, I get it working now… I think this feature should be added to Phoenix core, since it’s very basic functionality and I think everyone will need it.

Thanks anyway! :smiley:

2 Likes

It might be simpler to use the String module:

iex> test = "abcde fghij"
"abcde fghij"



iex > # Notice the space.
nil
iex> Phoenix.HTML.SimplifiedHelpers.Truncate.truncate(test, length: 9)         
"abcde ..."



iex> "#{String.slice(test, 0, 6)}..."
"abcde ..."
iex> "#{test |> String.slice(0, 6) |> String.trim_trailing}..."
"abcde..."
iex>
3 Likes