百科.dev
全部条目在线工具AI 编程趋势榜开源项目技术资讯提交条目
登录
< 返回工具列表
T

truncate_html

> 编程语言
开源

截断 HTML,这样您就不必再操心

312 stars0 点赞1 次浏览
访问官网GitHub

工具介绍

截断 HTML,这样您就不必再操心

TruncateHtml

truncate_html cuts off a string of HTML and takes care of closing any lingering open tags. There are many ways to solve this. This library does not have any dependencies, and parses HTML using regular expressions.

It can be used with or without Rails.

Example

ruby
some_html = '

This is a link

'
truncate_html(some_html, length: 15, omission: '...(continued)')
  => 

This...(continued)

A few notes:

  • By default, it will truncate on word boundary. To truncate the HTML string strictly at the specified length, pass in the word_boundary: false option.

  • If the input HTML is nil, it will return an empty string.

  • The omission text's length does count toward the resulting string's length.

  • `` tags will pass right through - they will not count toward the resulting string's length, or be truncated.

  • The default options are:

length: 100
omission: '...'
word_boundary: /\S/

You may also set global configuration options. For example, place the following on application boot, something like config/initializers/truncate_html.rb

ruby
TruncateHtml.configure do |config|
  config.length        = 50
  config.omission      = '...(continued)'
end

If you really want, you can even set a custom word boundary regexp. For example, to truncate at the end of the nearest sentence:

ruby
TruncateHtml.configure do |config|
  config.word_boundary = /\S[\.\?\!]/
end

You can also truncate the HTML at a specific point not based on length but content. To do that, place the :break_token in your source. This allows the truncation to be data driven, breaking after a leading paragraph or sentence. If the :break_token is in your content before the specified :length, :length will be ignored and the content truncated at :break_token. If the :break_token is in your content after the specified :length, :break_token will be ignored and the content truncated at :length.

ruby
TruncateHtml.configure do |config|
  config.break_token = ''
end

Installation

The latest gem version for the Rails 2.x series is 0.3.2. To use truncate_html on a Rails 2 app, please install the 0.3.2 version:

gem install truncate_html -v 0.3.2

For Rails 3, use the latest truncate_html:

gem install truncate_html

Issues or Suggestions

Found an issue or have a suggestion? Please report it on Github's issue tracker.

Testing

bash
bundle
rake

All green? Go hack.

Copyright (c) 2009 - 2010 Harold A. Giménez, released under the MIT license

Thanks to all the contributors!

Issues· 25 开放

查看全部 Issues在 GitHub 打开

暂无开放 Issues,或尚未同步最近议题。

> 标签

Ruby

暂无评论,来聊聊你的看法吧

> 工具信息

发布日期2026年8月1日
最后更新2026年9月18日
分类编程语言
定价开源

> 相关工具

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言