【问题标题】:Specifying a layout and a template in a standalone (not rails) ruby app, using slim or haml使用 slim 或 haml 在独立(不是 rails)的 ruby​​ 应用程序中指定布局和模板
【发布时间】:2011-10-26 21:41:12
【问题描述】:

我正在尝试在独立(不是 Rails)应用程序中做这样的事情:

layout.slim:

h1 Hello
.content
  = yield

show.slim:

= object.name
= object.description

我不知道如何指定布局和模板。 slim(或haml)可以做到这一点吗?谢谢。

【问题讨论】:

    标签: ruby haml slim-lang


    【解决方案1】:

    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>
    

    【讨论】:

    • 谢谢!我与文档非常接近,但我对范围是什么感到困惑。我还必须做== yield 而不是= yield
    • 哦,是的,很抱歉,Slim 默认会转义 HTML。我更新了代码。
    • 使用File.read("layout.slim") 而不是File.open("contents.slim", "rb").read。后者依赖 GC/finalizer 来关闭文件,这可能会发生也可能不会发生。
    猜你喜欢
    • 2011-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-22
    • 2011-06-27
    • 1970-01-01
    • 1970-01-01
    • 2013-06-28
    相关资源
    最近更新 更多