【问题标题】:Truncate text in Phoenix FrameworkPhoenix框架中截断文本
【发布时间】:2017-03-16 21:48:32
【问题描述】:

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

最好的方法是什么?

类似:

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

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

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

或者 - 我可以在数据创建/保存到数据库时创建一个摘录字段吗?

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

【问题讨论】:

标签: elixir phoenix-framework ecto


【解决方案1】:
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)

应该没问题

【讨论】:

  • 请注意,String.slice(text, 0..50) 将是前 51 个字符(从零开始)。 String.slice(text, 0, 50) 将是前 50 个字符。
猜你喜欢
  • 2012-07-23
  • 1970-01-01
  • 2023-03-21
  • 2015-07-06
  • 2017-11-05
  • 1970-01-01
  • 1970-01-01
  • 2014-02-23
  • 2021-05-16
相关资源
最近更新 更多