我在 Sinatra 中有一个 Haml 部分来处理我所有的“页面打开”项目,比如元标签。

我希望在此部分中为 page_title 设置一个变量,然后为每个 View 设置该变量。

部分是这样的:

%title @page_title

然后在 View 中,允许执行以下操作:
@page_title = "This is the page title, BOOM!"

我已经阅读了很多问题/帖子等,但我不知道如何寻求我正在尝试做的事情的解决方案。我来自 Rails,我们的开发人员通常使用 content_for 但他们设置了所有这些。我真的很想了解这是如何工作的。似乎我必须定义它并以某种方式使用 :locals 但我还没有弄清楚。预先感谢您提供任何提示!

最佳答案

您可以像这样将变量传递给 Sinatra haml 部分:

页面.haml

!!!
%html{:lang => 'eng'}
    %body
        = haml :'_header', :locals => {:title => "BOOM!"}

_header.haml
   %head
       %meta{:charset => 'utf-8'}
       %title= locals[:title]

在页面标题的情况下,我只是在我的布局中做这样的事情顺便说一句:

布局文件
%title= @title || 'hardcoded title default'

然后在路由中设置@title 的值(使用帮助器保持简短)。

但是,如果您的标题是部分标题,那么您可以将两个示例组合起来,例如:

布局文件
!!!
%html{:lang => 'eng'}
    %body
        = haml :'_header', :locals => {:title => @title}

_header.haml
   %head
       %meta{:charset => 'utf-8'}
       %title= locals[:title]

应用程序
helpers do
  def title(str = nil)
    # helper for formatting your title string
    if str
      str + ' | Site'
    else
      'Site'
    end
  end
end


get '/somepage/:thing' do
  # declare it in a route
  @title = title(params[:thing])
end

关于sinatra - 如何在带有 Haml 部分的 Sinatra 中使用本地(或每个 View )变量?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11589346/

10-12 12:59
查看更多