Nanoc»Helpers

The following is a list of all helpers that come bundled with Nanoc.

Helpers need to be activated before they can be used. For details on how to do so, see the Helpers page.

Blogging

Provides functionality for building blogs, such as finding articles and constructing feeds.

This helper requires all blog articles to have the kind attribute set to "article", and created_at set to the article’s publication timestamp. Some functions in this blogging helper, such as the #atom_feed function, require additional attributes to be set; these attributes are described in the documentation for these functions.

All time objects in item attributes, site configuration attributes or method parameters can either be a Time instance, or a string in any format parseable by Time.parse.

#articles()Array

Returns an unsorted list of articles, i.e. items where the kind attribute is set to "article".

#sorted_articles()Array

Returns a sorted list of articles, i.e. items where the kind attribute is set to "article". Articles are sorted by descending creation date, so newer articles appear before older articles.

#atom_feed()String

Returns a string representing the atom feed containing recent articles, sorted by descending creation date.

For this method to be useful, the following attributes must be set on blog articles:

title
The title of the blog post
created_at
(described above)
kind
(described above) — optional if you are passing an explicit list of articles using the :articles parameter

The following attributes can optionally be set on blog articles to change the behaviour of the Atom feed:

excerpt
An excerpt of the article, which is usually only a few lines long.
custom_path_in_feed
The path that will be used instead of the normal path in the feed. This can be useful when including non-outputted items in a feed; such items could have their custom feed path set to the blog path instead, for example.
custom_url_in_feed
The url that will be used instead of the normal url in the feed (generated from the site’s base url + the item rep’s path). This can be useful when building a link-blog where the URL of article is a remote location.
updated_at
The time when the article was last modified. If this attribute is not present, the created_at attribute will be used as the time when the article was last modified.

The site configuration will need to have the following attributes:

base_url
The URL to the site, without trailing slash. For example, if the site is at http://example.com/, the base_url would be "http://example.com".

The feed item will need to know about the feed title, the feed author name, and the URI corresponding to the author. These can be specified using parameters, as attributes in the feed item, or in the site configuration.

title
The title of the feed, which is usually also the title of the blog.
author_name
The name of the item’s author.
author_uri
The URI for the item’s author, such as the author’s website URL.

The feed item can have the following optional attributes:

feed_url
The custom URL of the feed. This can be useful when the private feed URL shouldn’t be exposed; for example, when using FeedBurner this would be set to the public FeedBurner URL.

To construct a feed, create a new item and make sure that it is filtered with :erb or :erubis; it should not be laid out. Ensure that it is routed to the proper path, e.g. /blog.xml. It may also be useful to set the is_hidden attribute to true, so that helpers such as the sitemap helper will ignore the item. The content of the feed item should be <%= atom_feed %>.

Here is an example for defining compilation and routing rules for a feed item:

compile '/blog/feed/' do
  filter :erb
  write '/blog.xml'
end

Here is an example for limiting the number of items in a feed:

<%= atom_feed limit: 10 %>

The #atom_feed function takes the following options:

:limit (Number)
The maximum number of articles to show. By default, 5 items will be included.
:articles (Array)
A list of articles to include in the feed. By default, the list of items returned by #articles function will be used.
:preserve_order (Boolean)
Whether or not the ordering of the list of articles should be preserved. If false or unspecified, the articles will be sorted by created_at. If true, the list of articles will be used as-is, and is assumed to end with the most recent article.
:content_proc (Proc)
A proc that returns the content of the given article, which is passed as a parameter. This function may not return nil. By default, it will return the compiled content of item at the :pre snapshot.
:excerpt_proc (proc)
A proc that returns the excerpt of the given article, passed as a parameter. This function should return nil if there is no excerpt. By default, it will return the content of the excerpt attribute of the item.
:title (String)
The feed's title, if it is not given in the item attributes.
:author_name (String)
The name of the feed's author, if it is not given in the item attributes.
:author_uri (String)
The URI of the feed's author, if it is not given in the item attributes.
:icon (String)
The URI of the feed's icon.
:logo (String)
The URI of the feed's logo.
url_for(item)String

Returns the URL for the given item. It will return the URL containing the custom path in the feed if possible, otherwise the normal path.

feed_url()String

Returns the URL of the feed. It will return the custom feed URL if set, or otherwise the normal feed URL.

atom_tag_for(item)String

Returns an URI containing an unique ID for the given item. This will be used in the Atom feed to uniquely identify articles. These IDs are created using a procedure suggested by Mark Pilgrim and described in his “How to make a good ID in Atom” blog post.

attribute_to_time(arg)Time

Converts the given attribute (which can be a string, a Time, a Date or a DateTime) into a Time. When given a Date instance or a string, the argument is assumed to be in the local timezone.

The Breadcrumbs helper provides support for breadcrumbs, which allow the user to go up in the page hierarchy.

This helper currently only works with legacy identifiers, and is not compatible with full identifiers.
#breadcrumbs_trail() → Array

Creates a breadcrumb trail leading from the current item to its parent, to its parent’s parent, etc, until the root item is reached. This function does not require that each intermediate item exist; for example, if there is no /foo/ item, breadcrumbs for a /foo/bar/ item will contain a nil element.

This function returns an array containing the breadcrumbs, starting with the root item and ending with the item itself.

Examples

Getting the breadcrumbs for the /projects/nanoc/history/ item, assuming that there is no /projects/ item:

breadcrumbs_trail
# => [
#   <Item* identifier="/">,
#   nil,
#   <Item* identifier="/projects/nanoc/">,
#   <Item* identifier="/projects/nanoc/history/">,
# ]

Capturing

The Capturing helper provides functionality for capturing content in one place and reusing this content elsewhere.

For example, suppose you want the sidebar of your site to contain a short summary of the item. You could put the summary in the meta file, but that’s not possible when the summary contains eRuby. You could also put the sidebar inside the actual item, but that’s not very pretty. Instead, you write the summary on the item itself, but capture it, and print it in the sidebar layout.

This helper has been tested with ERB and Haml. Other filters may not work correctly.

content_for(name, params = {}, &block)nil

Captures the content inside the block and stores it so that it can be referenced later on. This same method, is used for getting the captured content as well as setting it. When capturing, the content of the block itself will not be outputted.

This function takes the following arguments:

name (Symbol, String)
The base name of the attribute into which the content should be stored

By default, capturing content with the same name will raise an error if the newly captured content differs from the previously captured content. This behavior can be changed by providing a different :existing option to this method:

:error
When content already exists and is not identical, raise an error.
:overwrite
Overwrite the previously captured content with the newly captured content.
:append
Append the newly captured content to the previously captured content.
content_for(item, name)String

Fetches the capture with the given name from the given item and returns it.

This function takes the following arguments:

item (Item)
The item for which to get the capture
name (Symbol, String)
The name of the capture to fetch
capture(&block)String

Evaluates the given block and returns its contents. The contents of the block is not outputted.

Examples

Capturing the content for summary:

<% content_for :summary do %>
  <p>On this item, Nanoc is introduced, blah blah.</p>
<% end %>

Showing captured content in a sidebar:

<div id="sidebar">
  <h3>Summary</h3>
  <%= content_for(@item, :summary) || '(no summary)' %>
</div>

ChildParent

The ChildParent helper provides functionality for fetching the children and the parent of a given item. This works for both full identifiers and legacy identifiers.

#parent_of(item)

Returns the parent of the given item.

For items with legacy identifiers, the parent is the item where the identifier contains one less component than the identifier of the given item. For example, the parent of the /projects/nanoc/ item is the /projects/ item.

For items with full identifiers, the parent is the item where the identifier contains one less component than the identifier of the given item, and ends with any extension. For example, the parent of the /projects/nanoc.md item could be the /projects.md item, or the /projects.html item, etc. Note that the parent is ambiguous for items that have a full identifier; only the first candidate parent item will be returned.

#children_of(item)

Returns the children of the given item.

For items with legacy identifiers, the children are the items where the identifier contains one more component than the identifier of the given item. For example, the children of the /projects/ item could be /projects/nanoc/ and /projects/cri/, but not /about/ nor /projects/nanoc/history/.

For items with full identifiers, the children are the item where the identifier starts with the identifier of the given item, minus the extension, followed by a slash. For example, the children of the /projects.md item could be the /projects/nanoc.md and /projects/cri.adoc items , but not /about.md nor /projects/nanoc/history.md.

Filtering

The Filtering helper provides functionality for filtering parts of an item or a layout.

#filter(filter_name, arguments = {}, &block)

Filters the content in the given block with the filter_name filter, and outputs it. The arguments argument is passed as-is to the filter. This function does not return anything; instead, the filtered contents is directly appended to the output buffer (_erbout).

This function has been tested with ERB and Haml, as both filters use the _erbout variable. Other filters may not work correctly.

Examples

Running the :rubypants filter on a specific paragraph:

<p>Lorem ipsum dolor sit amet...</p>

<% filter :rubypants do %>
  <p>Consectetur adipisicing elit...</p>
<% end %>

HTMLEscape

The HTMLEscape helper contains functionality for HTML-escaping strings. Only the characters &, <, >, and " are escaped.

html_escape(string = nil, &block)
When given a string, returns the HTML-escaped representation of the given string. When given a block, the contents of the block will be escaped and appended to the output buffer, _erbout.

Examples

Escaping a string:

h('<br>')
# => '&lt;br&gt;'

Escaping with a block:

<% h do %>
  <h1>Hello <em>world</em>!</h1>
<% end %>

The buffer will now contain &lt;h1&gt;Hello &lt;em&gt;world&lt;/em&gt;!&lt;/h1&gt;.

LinkTo

The LinkTo helper contains functions for linking to items and item representations.

link_to(text, target, attributes = {})String

Creates an HTML link to the given path or item representation, and with the given text. All attributes of the a element, including the href attribute, will be HTML-escaped; the contents of the a element, which can contain markup, will not be HTML-escaped.

This function takes the following arguments:

text (String)
The visible link text
target (String, Item)
The path/URL, item or item representation that should be linked to
attributes (Hash)
A hash containing HTML attributes (e.g. rel, title, …) that will be added to the link.
link_to_unless_current(text, target, attributes = {})String

Creates an HTML link using #link_to, except when the linked item is the current one. In this case, a span element with class active and with the given text will be created. The HTML-escaping rules for #link_to apply here as well.

This function takes the following arguments:

text (String)
The visible link text
target (String, Item)
The path/URL, item or item representation that should be linked to
attributes (Hash)
A hash containing HTML attributes (e.g. rel, title, …) that will be added to the link.
relative_path_to(target)String

Returns the relative path from the current item to the given path or item representation. The returned path will not be HTML-escaped.

This function takes the following arguments:

target (String, Item)
The path/URL, item or item representation to which the relative path should be generated

Examples

Linking to a path:

link_to('Blog', '/blog/')
# => '<a href="/blog/">Blog</a>'

Linking to an item:

about = @items.find { |i| i.identifier == '/about/' }
link_to('About Me', about)
# => '<a href="/about.html">About Me</a>'

Linking to an item representation:

about = @items.find { |i| i.identifier == '/about/' }
link_to('My vCard', about.rep(:vcard))
# => '<a href="/about.vcf">My vCard</a>'

Linking with custom attributes:

link_to('Blog', '/blog/', :title => 'My super cool blog')
# => '<a title="My super cool blog" href="/blog/">Blog</a>'

Linking to a different page, unless current:

link_to_unless_current('Blog', '/blog/')
# => '<a href="/blog/">Blog</a>'

Linking to the same page, unless current:

link_to_unless_current('This Item', @item)
# => '<span class="active">This Item</span>'

Finding the relative path to an item:

# (assuming that the current item’s path is /foo/bar/)
relative_path_to('/foo/qux/')
# => '../qux/'

Rendering

The Rendering helper provides functionality for rendering layouts as partials.

render(identifier, other_assigns = {}, &block)

Renders the given layout. The given layout will be run through the first matching layout rule.

When this method is invoked without a block, the return value will be the rendered layout (a string) and _erbout will not be modified.

When this method is invoked with a block, an empty string will be returned and the rendered content will be appended to _erbout. In this case, the content of the block will be captured (using the Capturing) and this content will be made available with yield. In other words, a yield inside the partial will output the content of the block passed to the method.

The reason why #render with a block has this behaviour of returning an empty string and modifying _erbout is because the syntax of ERB does not allow combining the <%= ... %> form with a method call that takes a block.

The assigns (@item, @config, …) will be available in the partial. It is also possible to pass custom assigns to the method; these assigns will be made available as instance variables inside the partial.

This function takes the following arguments:

identifier (String)
The identifier of the layout that should be rendered
other_assigns (Hash)
A hash containing extra assigns that will be made available as instance variables in the partial

Examples

Rendering a head and a foot partial around some text:

<%= render 'head' %> - MIDDLE - <%= render 'foot' %>

This example returns "HEAD - MIDDLE - FOOT".

Rendering a head partial with a custom title:

<!-- The 'head' layout -->
<h1><%= @title %></h1>

<!-- The item/layout where the partial is rendered -->
<%= render 'head', :title => 'Foo' %>

This example returns "<h1>Foo</h1>".

Yielding inside a partial:

<!-- The 'box' partial -->
<div class="box">
  <%= yield %>
</div>

<!-- The item/layout where the partial is rendered -->
<% render 'box' do %>
  I'm boxy! Luvz!
<% end %>

<!-- Result -->
<div class="box">
  I'm boxy! Luvz!
</div>

Tagging

The Tagging helper provides support for managing tags added to items.

To add tags to items, set the tags attribute to an array of tags that should be applied to the item. For example:

tags: [ 'foo', 'bar', 'baz' ]
tags_for(item, base_url:, none_text:, separator:)String

Returns a formatted list of tags for the given item as a string. The tags will be linked using the #link_for_tag function; the HTML-escaping rules for #link_for_tag apply here as well.

This function takes the following arguments:

base_url (String, nil)
The URL to which the tag will be appended to construct the link URL. This URL must have a trailing slash. The function will return a tags string without tag page link if the param is not provided.
none_text (String)
The text to display when the item has no tags. By default, '(none)' will be used.
separator (String)
The separator to put between tags. By default, ', ' will be used, so that tags are comma-separated.
items_with_tag(tag)String

Find all items with the given tag.

This function takes the following arguments:

tag (String)
The tag for which to find all items
link_for_tag(tag, base_url)String

Returns a link to to the specified tag. The link is marked up using the rel-tag microformat. The href attribute of the link will be HTML-escaped, as will the content of the a element.

This function takes the following arguments:

tag (String)
The name of the tag, which should consist of letters and numbers (no spaces, slashes, or other special characters).
base_url (String)
The URL to which the tag will be appended to construct the link URL. This URL must have a trailing slash.

Text

The Text helper contains several useful text-related helper functions.

excerptize(string, length: 25, omission: '...')String

Returns an excerpt for the given string. HTML tags are ignored, so if you don't want them to turn up, they should be stripped from the string before passing it to the excerpt function.

This function takes the following arguments:

string (String)
The string for which to build an excerpt
length (Integer)
The maximum number of characters this excerpt can contain, including the omission.
omission (String)
The string to append to the excerpt when the excerpt is shorter than the original string
strip_html(string)String

Strips all HTML tags out of the given string.

This function takes the following arguments:

string (String)
The string from which to strip all HTML

XMLSitemap

The XMLSitemap helper contains functionality for building XML sitemaps that will be crawled by search engines. See the Sitemaps protocol site for details.

xml_sitemap(params = {})String

Builds an XML sitemap and returns it.

The following attributes can optionally be set on items to change the behaviour of the sitemap:

changefreq
The estimated change frequency as defined by the Sitemaps protocol
priority
The item's priority, ranging from 0.0 to 1.0, as defined by the Sitemaps protocol

The sitemap will also include dates on which the items were updated. These are generated automatically; the way this happens depends on the used data source (the filesystem data source checks the file mtimes, for instance).

The site configuration will need to have the following attributes:

base_url
The URL to the site, without trailing slash. For example, if the site is at "http://example.com/", the base_url would be "http://example.com".

This function takes the following options:

:items (Array)
A list of items to include in the sitemap
:rep_select (Proc)
A proc to filter reps through. If the proc returns true, the rep will be included; otherwise, it will not.

Examples

Typically, the value for the :items option to the #xml_sitemap method will be all items with a path that ends in .html. For example:

<%= xml_sitemap(items: items.select { |i| i.path.end_with?('.html') }) %>

If you want to hide certain items from the XML sitemap, you can add is_hidden: true to the frontmatter of those items, and then exclude such items from the XML sitemap:

<%= xml_sitemap(
  items: items.select { |i| !i[:is_hidden] && i.path.end_with?('.html') }
) %>