本文介绍了使用slim或haml在独立(非Rails)ruby应用程序中指定布局和模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试在独立的应用程序(而不是Rails)中执行以下操作:
I'm trying to do something like this in a standalone (not rails) app:
layout.slim:
layout.slim:
h1 Hello
.content
= yield
show.slim:
show.slim:
= object.name
= object.description
我不知道如何指定布局和模板.苗条(或haml)有可能吗?谢谢.
I can't figure out how to specify a layout and a template. Is this possible with slim (or haml)? Thanks.
推荐答案
layout.slim文件如下:
The layout.slim file looks like:
h1 Hello
.content
== yield
contents.slim文件如下:
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 }
这将输出:
<h1>Hello</h1><div class="content">test this layout</div>
这篇关于使用slim或haml在独立(非Rails)ruby应用程序中指定布局和模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!