【问题标题】:SLIM template in Rails: How to render html element from instance variable?Rails 中的 SLIM 模板:如何从实例变量呈现 html 元素?
【发布时间】:2012-07-11 20:38:45
【问题描述】:
  • 红宝石 1.9.2p290
  • 导轨 3.1.1

如何从 SLIM 模板中的控制器创建 html 元素?

我会解释:

在我看来,我想通过一些条件来改变“h1”的html标签。

但我想将逻辑放在控制器中。

case params[:controller] when "recipes", "chefs"
    case params[:action] when "show", "index"
      @h_number = "h2"
    else
      @h_number ="h1"
    end
  else
    @h_number ="h1"
end

在我的 SLIM 视图中,我想要这样的东西:

= @h_number#logo
    = link_to image_tag("image.png"), root_path

结果:

<h1 id="logo"><a href="/"><img src="image.png"></a></h2>

<h2 id="logo"><a href="/"><img src="image.png"></a></h2>

有可能吗?

我说清楚了吗?对不起我的英语。

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3.1 haml slim-lang


    【解决方案1】:

    我非常怀疑这是可能的。但是你总是可以创建一个辅助方法来做到这一点

    在您的应用程序帮助文件中,

    module ApplicationHelper
        def logo
            num = case params[:controller] when "recipes", "chefs"
              case params[:action] when "show", "index" then 2 end
            end || 1
    
            "<h#{num}>" + link_to(image_tag("image.png"), root_path) + "</h#{num}>"
        end
    end
    

    在您的模板中

    body
      header
        == logo
    

    而且你的控制器不需要任何东西。

    【讨论】:

    • 谢谢!我是新来的铁路!你的答案对我来说是完美的。
    • 这是一个旧线程,但我认为对于像我这样开始的人来说值得一提。双等号 (==) 在没有 escape_html 方法的情况下生成输出。
    猜你喜欢
    • 2011-03-08
    • 2012-12-11
    • 2019-06-25
    • 1970-01-01
    • 2011-12-27
    • 2015-10-27
    相关资源
    最近更新 更多