Skip to content

Helper methods

Devin edited this page Jul 1, 2020 · 7 revisions

Frontman ships with a few helper method that are globally available in your templates. You can also define custom helper methods.

Default helper methods

current_tree

Returns the SitemapTree belonging to the current page.

current_page

Returns the Resource belonging to the current page.

slugify

Converts any string into a slug.

slugify('This is a string') # outputs "this-is-a-string"

format_url

Formats a given relative URL into a pretty URL.

format_url('about/index.html') # outputs "/about/"
format_url('/about') # outputs "/about/"

render_markdown

Parses a given Markdown string and compiles it into HTML.

render_markdown('# Hello, world!') # outputs "<h1 id=\"hello-world\">Hello, world!</h1>"

render_erb

Parses a given ERB string and executes the Ruby code in it. You can pass data to your template string with the second parameter.

render_erb('<%= 'Hello, ' + hello_to %>', hello_to: 'world') # outputs "Hello, world!"

Custom helper methods

You can define custom helper modules and make them available by registering them in your config.rb file. All your helpers must be in the same directory, and their filenames must end with _helper.rb.

For example, let's say you define a CustomHelper module in helpers/custom_helper.rb.

module CustomHelper
  def custom_method
    "Hello, world!"
  end
end

You can register this helper and all other which are in the same directory in your config.rb file.

register_helper_dir('helpers')

Once you've registered your helpers, you can use the methods in your pages and layouts directly.

The custom method says: <%= custom_method %>.

Because helpers are global, you should always use a unique method names across your project.

Clone this wiki locally