在 Phoenix Framework 中截断文本

Truncate text in Phoenix Framework

我有一个名为内容的文本字段,我需要显示其中的摘录。

最好的方法是什么?

类似于:

<% post.content.slice(0..50) %>

是我的想法;但是,这给了我一个参数错误。

显示内容文本字段前 50 个字符的最佳方式是什么?

或者 - 当数据 created/saved 进入数据库时​​,我可以创建一个摘录字段吗?

感谢任何帮助。提前致谢。

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

这就是我在我的应用程序中使用的,我相信我无耻地从某个地方复制粘贴了它,但它工作得很好,显然你可以根据你的需要修改它。

但是如果你不需要这个花哨的东西那么

String.slice(post.content, 0..50)

应该可以正常工作