加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby – Sinatra:如何在Mustache视图中使用帮助器

发布时间:2020-12-17 02:01:49 所属栏目:百科 来源:网络整理
导读:我想在Mustache视图中使用我的Sinatra帮助器方法. 我这样做: # in app.rb:...helpers do def helloworld "helloworld!" endendget '/' mustache :homeend...# in views/homeclass App Sinatra::Base module Views class Home Mustache def hello helloworld
我想在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>

它不起作用,我有错误信息:

?undefined局部变量或方法`helloworld’for App :: Views :: Home:0x000000023ebd48?

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

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

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

非常感谢您的帮助!

解决方法

您应该可以使用模块执行某些操作:

# 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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读