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

北城以北 提交于 2019-12-03 01:05:45

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>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!