Is there an easy way of referring to the public directory in Sinatra?
Imagine this structure:
/project
/templates
view1.haml
view2.haml
开发者_JS百科 misc_views/
view3.haml
view4.haml
even_deeper/
view5.haml
/public
script1.js
The depth of the templates can vary, and I would like to refer to the public directory if I want to include some files from it. Is there a helper or some other gimmick that takes me to the public directory? It seems bad to have something like ../../../public/script1.js , or ../../public/script1.js in my views. Surely there must be a better way.
You can use the settings.public
configuration to refer to the public directory. For example:
get "/" do
js = File.join( settings.public, 'script1.js' )
File.exists?( js ) #=> true
end
As this is an absolute path, there is no need to make it relative to your view to get the file. You could reach out to this from your view, but I would personally set the path as an instance variable from the controller.
get "/" do
# If you really only need the directory
@public = settings.public
# If you actually need the path to a specific file
@main = File.join( settings.public, 'main.js' )
# If you actually need the contents of a file
@js = IO.read( File.join( settings.public, 'main.js' ) )
end
You must include the static resources by the root of the web address or a relative request path, as it will be the browser who requests it, not your server-side code. Unless I am mistaken in your case?
<script type="text/javascript" src="/script1.js"></script>
精彩评论