使用 slim 或 haml 在独立(非 Rails)Ruby 应用程序中指定布局和模板

发布于 2024-11-29 16:05:57 字数 243 浏览 2 评论 0原文

我正在尝试在独立(不是rails)应用程序中执行类似的操作:

layout.slim:

h1 Hello
.content
  = yield

show.slim:

= object.name
= object.description

我无法弄清楚如何指定布局和模板。 slim(或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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

洋洋洒洒 2024-12-06 16:05:57

layout.slim 文件如下所示:

h1 Hello
.content
  == yield

Contents.slim 文件如下所示:

= name

这可以缩短,但出于解释目的,我将其分为各个步骤。

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>

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>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文