[英]How to include an external JavaScript file in Haml
我想添加 styles 並使用外部 JavaScript 和 jQuery 文件動態運行,但它不斷拋出錯誤。
Ruby代碼為:
# 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
哈姆爾代碼是:
!!!
%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 "actions"
錯誤是當我在瀏覽器中運行應用程序時:
NoMethodError at /
undefined method `javascript_include_tag' for #<Sinatra::Application:"some hex address here">
沒有那行代碼它運行良好,嵌入式 JavaScript 也可以工作。 我無法鏈接外部 JavaScript 文件。
當您的目錄如下所示時:
ruby-web/
| public/
|-| css/
|-|-| styles.css
|
|-| javascript/
|-|-| jquery-3.5.1.min.js
|-|-| actions.js
|
| views/
|-| index.haml
|-| about.haml
| my-app.rb
您的 Ruby 代碼如下所示:
# 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"
不是:
:src => "public/javascript/actions.js"
和
:href => "public/css/styles.css"
即使腳本和 styles 在public
文件夾中。
也不:
:src => "../public/javascript/actions.js"
和
:href => "../public/css/styles.css"
即使腳本和 styles 相對於 index.haml 位於../public/javascript/
或../public/css/
中index.haml.
現在你有了一個包含腳本和 styles 的公用文件夾,你可以用上面提到的方法鏈接到它們。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.