【问题标题】:Rails - how to add an html attribute to a layout tagRails - 如何将 html 属性添加到布局标签
【发布时间】:2012-09-20 19:23:17
【问题描述】:

这是我的应用程序布局页面的外观(这是其中的一部分)

%html
  %body
    #main
      .content
        = yield

有时(并非总是)我需要将“id”属性添加到.contentdiv。如何从html.haml 页面执行此操作?

注意:我的意思不是在运行时使用 javascript 来做。

更新:谢谢,但我忘了提到每个页面的这个“id”不同。换句话说,每个html.haml 页面可能有自己的.content 的“id”。

【问题讨论】:

    标签: html ruby-on-rails ruby haml


    【解决方案1】:

    还有一个解决方案:

    %html
      %body
        #main
          .content{id: @content_id}
            = yield
    
    #some .html.haml page
    - @content_id = "my_id"
    

    如果您不定义 @content_id,那么 .content 将没有 id。

    【讨论】:

      【解决方案2】:

      您可以根据需要菊花链 id 和类

      %html
        %body
          #main
            .content#random-id.random-class
              = yield
      

      【讨论】:

        【解决方案3】:

        您可以这样做以将 id 等属性添加到标签:

        .content{:id => "foo"}
        

        【讨论】:

          【解决方案4】:

          您可以通过ruby a Hash添加属性并通过条件表达式设置值。

          %html
            %body
              #main
                .content{:id => (id_needed ? 'my_id' : nil)}
                  = yield
          

          【讨论】:

          • 或更短:.content{:id => id_neded && 'my_id'}
          猜你喜欢
          • 2014-01-15
          • 2021-06-17
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-05-29
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多