我如何在haml中包含外部.js文件,该文件与ruby和sinatra一起运行?

问题描述 投票:0回答:1

我想通过外部JavaScript和jQuery文件动态添加样式和功能

但是它一直在抛出错误。

红代码:

# myapp.rb
require 'sinatra'
require 'sinatra/reloader'
require 'haml'

get '/' do
    @contacts = [
        {
            name: "Petit",
            class: "K1"
        }
    ]

    haml :index
end

get '/about-us' do
    haml :about
end

haml代码:

!!!
%html
    %head
        = javascript_include_tag "actions"

    %body
        %h1#title.titles
            This is a page title

        %ul
            - @contacts.each do |contact|
                %li
                    = "#{contact[:name]}'s class is #{contact[:class]}"

        %a{ href: "/about-us"}
            About

错误:当我在浏览器上运行应用程序时,这行似乎是问题所在

= javascript_include_tag“操作”

NoMethodError at /
undefined method `javascript_include_tag' for #<Sinatra::Application:"some hex address here">

没有该行代码,该应用程序就可以很好地运行,并且嵌入式javascript也可以工作。我只是似乎无法链接外部.js文件。在HTML中很容易。

javascript jquery ruby sinatra haml
1个回答
0
投票

知道了!

所以当您的目录看起来像这样:

ruby-web/
| public/
|-| css/
|-|-| styles.css
|
|-| javascript/
|-|-| jquery-3.5.1.min.js
|-|-| actions.js
|
| views/
|-| index.haml
|-| about.haml
| my-app.rb

您的红宝石代码如下:

# myapp.rb
require 'sinatra'
require 'sinatra/reloader'
require 'haml'

get '/' do
    haml :index
end

get '/about-us' do
    haml :about
end

您的index.haml。该页面将成为连接到服务器时将显示的根页面。因此,您的index.haml代码应如下所示:

!!!
%html
    %head
        /Styles :
        %link{:href => "css/styles.css", :type => "text/css"}
        /Scripts :
        %script{:src => "javascript/jquery-3.5.1.min.js", :type => "text/javascript"}
        %script{:src => "javascript/actions.js", :type => "text/javascript"}

    %body
        %h1#title
            Equations

        %div#about
            %footer#footer
                %a{ href: "/about-us"}
                    About

注意haml代码中的%link%script标记,现在查看:src:href中给出的路径。

它是:src => "javascript/actions.js":href => "css/styles.css"

NOT:src => "public/javascript/actions.js":href => "public/css/styles.css"。即使脚本和样式位于public文件夹中。

NOR:src => "../public/javascript/actions.js":href => "../public/css/styles.css"。即使相对于../public/javascript/,脚本和样式位于../public/css/index.haml.中>

现在您已经有了一个公共文件夹,其中包含脚本和样式,您可以使用上述方法将它们相应地链接起来。 :-)

© www.soinside.com 2019 - 2024. All rights reserved.