ruby-on-railsrubymodel-view-controllerslim-langnanoc

Pass variable from content to layout in Nanoc using Slim


I basically want to know the easiest way to pass a ruby variable from a content page to its layout using Nanoc and Slim. I am thinking of something like this:

content/content.slim:

---
title: Writeups
layout: /layout.slim
---
- age = get_age

layout/layout.slim:

doctype html
  html
    head
      == yield
      p I am #{@item[:title]} and am #{@item[:age]} years old

I know how to access values via frontmatter, but frontmatter values are fixed and what I want is a ruby function to find that value for me.


Solution

  • Nanoc provides a capturing helper, which makes it possible to “capture” content in one place and use it somewhere else.

    content/content.slim:

    ---
    title: Mister Tree
    ---
    
    p Hello there!
    
    - content_for :age
      | hundreds of years
    

    layout/layout.slim:

    doctype html
    html
      body
        == yield
        p I am #{@item[:title]} and am #{content_for(@item, :age)} years old
    

    lib/default.rb (or any file in lib/ of your choosing):

    use_helper Nanoc::Helpers::Capturing
    

    This generates the following output:

    <!DOCTYPE html>
    <html>
      <body>
        <p>Hello there!</p>
        <p>I am Mister Tree and am hundreds of years years old</p>
      </body>
    </html>