Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specifying a layout and a template in a standalone (not rails) ruby app, using slim or haml

I'm trying to do something like this in a standalone (not rails) app:

layout.slim:

h1 Hello
.content
  = yield

show.slim:

= object.name
= object.description

I can't figure out how to specify a layout and a template. Is this possible with slim (or haml)? Thanks.

like image 903
chrismealy Avatar asked Aug 14 '11 19:08

chrismealy


People also ask

What is the layout in Ruby on Rails?

A layout defines the surroundings of an HTML page. It's the place to define a common look and feel of your final output. Layout files reside in app/views/layouts. The process involves defining a layout template and then letting the controller know that it exists and to use it.

How can you tell Rails to render without a layout?

By default, if you use the :text option, the text is rendered without using the current layout. If you want Rails to put the text into the current layout, you need to add the layout: true option.

How should you use nested layouts in rails?

Rails provides us great functionality for managing layouts in a web application. The layouts removes code duplication in view layer. You are able to slice all your application pages to blocks such as header, footer, sidebar, body and etc.


1 Answers

The layout.slim file looks like:

h1 Hello
.content
  == yield

The contents.slim file looks like:

= name

This can be shortened, but I separated to individual steps for explanation purposes.

require 'slim'

# Simple class to represent an environment
class Env
  attr_accessor :name
end

# Intialize it
env = Env.new
# Set the variable we reference in contents.slim
env.name = "test this layout"

# Read the layout file in as a string
layout = File.open("layout.slim", "rb").read

# Read the contents file in as a string
contents = File.open("contents.slim", "rb").read

# Create new template object with the layout
l = Slim::Template.new { layout }

# Render the contents passing in the environment: env
# so that it can resolve: = name
c = Slim::Template.new { contents }.render(env)

# Render the layout passing it the rendered contents
# as the block. This is what yield in layout.slim will get
puts l.render{ c }

This will output:

<h1>Hello</h1><div class="content">test this layout</div>
like image 199
stonean Avatar answered Sep 29 '22 20:09

stonean