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

sablon

> 编程语言
开源

基于 docx 模板和邮件合并字段的 Ruby 文档模板处理器。

464 stars0 点赞2 次浏览
访问官网GitHub

工具介绍

基于 docx 模板和邮件合并字段的 Ruby 文档模板处理器。

Sablon

Is a document template processor for Word docx files. It leverages Word's built-in formatting and layouting capabilities to make template creation easy and efficient.

Table of Contents

  • Installation
  • Usage
    • Writing Templates
      • Content Insertion
        • WordProcessingML
        • HTML
        • Images (Beta)
      • Conditionals
      • Loops
      • Nesting
      • Comments
    • Configuration (Beta)
      • Customizing HTML Tag Conversion
      • Customizing CSS Style Conversion
    • Executable
    • Examples
      • Using a Ruby script
      • Using the sablon executable
  • Contributing
  • Inspiration

Installation

Add this line to your application's Gemfile:

gem 'sablon'

Usage

require "sablon"
template = Sablon.template(File.expand_path("~/Desktop/template.docx"))
context = {
  title: "Fabulous Document",
  technologies: ["Ruby", "HTML", "ODF"]
}
template.render_to_file File.expand_path("~/Desktop/output.docx"), context

Writing Templates

Sablon templates are normal Word documents (.docx) sprinkled with MailMerge fields to perform operations. The following section uses the notation «=title» to refer to Word MailMerge fields.

A detailed description about how to create a template can be found here

Content Insertion

The most basic operation is to insert content. The contents of a context variable can be inserted using a field like:

«=title»

It's also possible to call a method on a context object using:

«=post.title»

NOTE: The dot operator can also be used to perform a hash lookup. This means that it's not possible to call methods on a hash instance. Sablon will always try to make a lookup instead.

This works for chained method calls and nested hash lookup as well:

«=buyer.address.street»
WordProcessingML

Generally Sablon tries to reuse the formatting defined in the template. However, there are situations where more fine grained control is needed. Imagine you need to insert a body of text containing different formats. If you can't decide the format ahead of processing time (in the template) you can insert WordProcessingML directly.

It's enough to use a simply insertion operation in the template:

«=long_description»

To insert WordProcessingML prepare the context accordingly:

word_processing_ml = 

this is bold text

XML

context = {
  long_description: Sablon.content(:word_ml, word_processing_ml)
}
template.render_to_file File.expand_path("~/Desktop/output.docx"), context

In the example above the entire paragraph will be replaced because all of the nodes being inserted aren't valid children of a paragraph (w:p) element. The example below shows inline insertion, where only runs are added and instead of replacing the entire paragraph only the merge field gets removed.

Important: All text must be wrapped in a run tag for valid inline insertion because WordML is still inserted directly into the document "as is" without any structure transformations other than run properties being merged.

word_processing_ml = 

this is bold text

XML

context = {
  long_description: Sablon.content(:word_ml, word_processing_ml)
}
template.render_to_file File.expand_path("~/Desktop/output.docx"), context
HTML

Similar to WordProcessingML it's possible to use html as input while processing the template. You don't need to modify your templates, a simple insertion operation is sufficient:

«=article»

To use HTML insertion prepare the context like so:

html_body = Table's can also be created via HTML
    

        Cell 1 only text
        
            

                
List in Table - 1

                
List in Table - 2

            

        
    

    

        
        
            
                
AB

                
CD

            
        
    

HTML
context = {
  article: Sablon.content(:html, html_body) },
  # Or use html: prefix to make sablon parse the value as HTML.
  # Does the same as above.
  'html:article' => html_body
}
template.render_to_file File.expand_path("~/Desktop/output.docx"), context

There is no 1:1 conversion between HTML and Open Office XML however, a large number of tags are very similar. HTML insertion is relatively complete covering several key content structures such as paragraphs, tables and lists. The snippet above showcases some of the capabilities present, for a comprehensive example please see the html insertion test fixture here. All html element conversions are defined in configuration.rb with their matching AST classes defined in ast.rb.

Basic conversion of CSS inline styles into matching WordML properties is possible using the style=" ... " attribute in the HTML markup. Not all CSS properties are supported as only a small subset of CSS styles have a direct Open Office XML equivalent. Styles are passed onto nested elements if the parent can't use them. The currently supported styles are also defined in configuration.rb. Toggle properties that aren't directly supported can be added using the text-decoration: style attribute with the proper XML tag name as the value (i.e. text-decoration: dstrike for w:dstrike). Simple single value properties that do not need a conversion can be added using the XML property name directly, omitting the w: prefix i.e. (highlight: cyan for w:highlight).

Table, Paragraph and Run property references can be found at:

  • http://officeopenxml.com/WPparagraphProperties.php
  • http://officeopenxml.com/WPtextFormatting.php
  • http://officeopenxml.com/WPtableProperties.php

The full Open Office XML specification used to develop the HTML converter can be found here (3rd Edition).

The example above shows an HTML insertion operation that will replace the entire paragraph. In the same fashion as WordML, inline HTML insertion is possible where only the merge field is replaced as long as only "inline" elements are used. "Inline" in this context does not necessarily mean the same thing as it does in CSS, in this case it means that once the HTML is converted to WordML only valid children of a paragraph (w:p) tag exist. As with WordML all plain text needs to be wrapped in a HTML tag. A simple .. tag enclosing all other elements will suffice. See the example below:

inline_html =  html_body
}
template.render_to_file File.expand_path("~/Desktop/output.docx"), context
Images (beta)

Images can be added to the document using a placeholder image wrapped in a pair of merge fields set up as «@figure:start» and «@figure:end». Where in this case "figure" is the key of the context hash storing the image.

Images are wrapped in an instance of a Sablon::Content class in the same fashion as HTML or WordML strings. An image may be initialized from multiple sources such as file paths, URLs, or any object that exposes a #read method that returns image data. When using a "readable object" if the object doesn't have a #filename method then a filename: '...' option needs to be added to the Sablon.content method call.

By default the inserted image takes the dimensions of the placeholder. The size of an image can also be defined dynamically by specifying width and height with unit (cm or in) in a properties hash like properties: {height: "2cm", width: "20cm"}

context = {
  figure: Sablon.content(:image, 'fixtures/images/c3po.jpg'),
  figure2: Sablon.content(:image, string_io_obj, filename: 'test.png'),
  figure3: Sablon.content(:image, string_io_obj, filename: 'test.png', properties: {height: '2cm', width: '2cm'})
  # alternative method using special key format for simple paths and URLs
  # 'image:figure' => 'fixtures/images/c3po.jpg'
}

Example:

Additional examples of usage can be found in images_template.docx and in sablon_test.rb.

Conditionals

Sablon can render parts of the template conditionally based on the value of a context variable. Conditional fields are inserted around the content.

«technologies:if»
    ... arbitrary document markup ...
«technologies:endIf»

This will render the enclosed markup only if the expression is truthy. Note that nil, false and [] are considered falsy. Everything else is truthy.

For more complex conditionals you can use a predicate like so:

«body:if(present?)»
    ... arbitrary document markup ...
«body:endIf»

Finally, you can also mix in elsif and else clauses as well.

«body:if(present?)»
    ... arbitrary document markup ...
«body:elsif(nil?)»
    ... arbitrary document markup ...
[additional elsif blocks...]
«body:else»
    ... arbitrary document markup ...
«body:endIf»

Loops

Loops repeat parts of the document.

«technologies:each(technology)»
    ... arbitrary document markup ...
    ... use `technology` to refer to the current item ...
«technologies:endEach»

Loops can be used to repeat table rows or list enumerations. The fields need to be placed in within table cells or enumeration items enclosing the rows or items to repeat. Have a look at the example template for more details.

Nesting

It is possible to nest loops and conditionals.

Comments

Sometimes it's necessary to include markup in the template that should not be visible in the rendered output. For example when defining sample numbering styles for HTML insertion.

«comment»
    ... arbitrary document markup ...
«endComment»

Configuration (Beta)

The Sablon::Configuration singleton is a new feature that allows the end user to customize HTML parsing to their needs without needing to fork and edit the source code of the gem. This API is still in a beta state and may be subject to change as future needs are identified beyond HTML conversion.

The example below show how to expose the configuration instance:

Sablon.configure do |config|
  # manipulate config object
end

The default set of registered HTML tags and CSS property conversions are defined in configuration.rb.

Customizing HTML Tag Conversion

Any HTML tag can be added using the configuration object even if it needs a custom AST class to handle conversion logic. Simple inline tags that only modify the style of text (i.e. the already supported `` tag) can be added without an AST class as shown below:

Sablon.configure do |config|
  config.register_html_tag(:bgcyan, :inline, properties: { highlight: 'cyan' })
end

The above tag simply adds a background color to text using the `` property.

More complex business logic can be supported by adding a new class under the Sablon::HTMLConverter namespace. The new class will likely subclass Sablon::HTMLConverter::Node or Sablon::HTMLConverter::Collection depending on the needed behavior. The current AST classes serve as additional examples and can be found in ast.rb. When registering a new HTML tag that uses a custom AST class the class must be passed in either by name using a lowercased and underscored symbol or the class object itself.

The block below shows how to register a new HTML tag that adds the fo

Issues· 38 开放

查看全部 Issues在 GitHub 打开

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

> 标签

Ruby

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

> 工具信息

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

> 相关工具

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