【问题标题】:Haml Inherit TemplatesHaml 继承模板
【发布时间】:2011-02-27 01:12:50
【问题描述】:

我正在单独使用 Haml (Haml/Sass 3.0.9 - Classy Cassidy) 来生成静态 HTML。我想创建一个所有其他模板都继承的共享布局模板。

Layout.haml

%html
  %head
    %title Test Template
  %body
    .Content

Content.haml

SOMEHOW INHERIT Layout.haml
SOMEHOW Change the title of the page "My Content".
  %p This is my content

生产:

Content.html

<html>
  <head>
    <title>My Content</title>
  </head>
  <body>
    <div class="Content">
      <p>This is my content</p>
    </div>
  </body>
</html>

但这似乎不可能。我已经看到在将 Haml 与 Rails 一起使用时使用渲染部分,但在单独使用 Haml 时找不到任何解决方案。

必须将布局代码放入我的所有模板中将是维护的噩梦;所以我的问题是如何避免这样做?有没有解决这个问题的标准方法?我错过了一些基本的东西吗?

我发现了一个类似的问题:Rendering HAML partials from within HAMLoutside of Rails

【问题讨论】:

    标签: html templates haml


    【解决方案1】:

    我已经创建了一个可以满足我需求的原型。我只需要将它创建为一个模块并允许它接受布局模板和内容模板作为参数(以及数据集)。

    require "haml"
    
    layoutTemplate = File.read('layout.haml')
    layoutEngine = Haml::Engine.new(layoutTemplate)
    layoutScope = Object.new
    
    output = layoutEngine.render(scope=layoutScope) { |x|
      case x
        when :title
          scope.instance_variable_get("@haml_buffer").buffer << "My Title\n"
        when :content
           contentTemplate = File.read('page.haml')
           contentEngine = Haml::Engine.new(contentTemplate)
           contentOutput = contentEngine.render
          scope.instance_variable_get("@haml_buffer").buffer << contentOutput
      end
    }
    
    puts output
    

    layout.haml

    %html
      %head
        %title
          - yield :title
      %body
        .content
          - yield :content
    

    page.haml

    %h1 Testing
    %p This is my test page.
    

    输出

    <html>
      <head>
        <title>
    My Title
        </title>
      </head>
      <body>
        <div class='content'>
    <h1>Testing</h1>
    <p>This is my test page.</p>
        </div>
      </body>
    </html>
    

    【讨论】:

      【解决方案2】:

      Haml 的构建假设它将与一些提供部分和布局等内容的 Ruby 框架一起使用。如果您想要一种简单的方法来呈现带有布局和部分的静态 Haml 代码,请查看 StaticMatic。

      【讨论】:

      • +1 谢谢,一直在看 StaticMatic。它提供了我想要的布局模板,但在其他领域引发了问题。
      【解决方案3】:

      StaticMatic 已被其创建者抛弃,现在使用 http://middlemanapp.com/

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-04-17
        • 2013-12-13
        • 2010-10-04
        • 2011-04-08
        • 2016-01-19
        • 2016-11-14
        • 2014-10-21
        相关资源
        最近更新 更多