【问题标题】:Sinatra : how to use helpers in Mustache viewsSinatra:如何在 Mustache 视图中使用助手
【发布时间】:2012-05-11 19:54:47
【问题描述】:

我想在 Mustache 视图中使用我的 Sinatra 辅助方法。

我这样做:

# in app.rb:
...
helpers do
  def helloworld
    "helloworld!"
  end
end
get '/'
  mustache :home
end
...

# in views/home
class App < Sinatra::Base
  module Views
    class Home < Mustache
      def hello
        helloworld
      end
    end
  end
end

# in home.mustache
<p>{{hello}}</p>

它不起作用,我收到错误消息:

«App::Views::Home:0x000000023ebd48 的未定义局部变量或方法 `helloworld'»

如何在 Mustache 视图中使用我的方法助手?

或者,我如何直接从 home.mustache 使用我的方法助手?像这样:

# in home.mustache
<p>{{helloworld}}</p>

非常感谢您的帮助!

【问题讨论】:

    标签: ruby sinatra mustache helpers


    【解决方案1】:

    你应该可以用一个模块做一些事情:

    # app_helpers.rb
    module AppHelpers
      def helloworld
        "helloworld!"
      end
    end
    
    # app.rb
    helpers AppHelpers
    
    get '/'
      mustache :home
    end
    
    # views/home.rb
    class App < Sinatra::Base
      module Views
        class Home < Mustache
          include AppHelpers
    
          def hello
            helloworld
         end
       end
     end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多