When including javascript or CSS in HAML you would normally have to do the following to include CSS:
%link{:type => "text/css", :rel => "stylesheet", :href => "/css/mycss.css"}
And for javascript:
%script{:type => "text/javascript", :src => "/js/myscript.js"}
I was wondering if HAML does not have a short way of including these tags (to get content from a source of course, not inline), that omits the need for the type
and rel
attributes, since these are invariable anyway.
Note that Ruby on Rails provides this feature via a function, but I'm not using rails.
To include JavaScript directly in a Haml view, use the nifty :javascript filter. Haml sees the contents as JavaScript and wraps them in a script tag when rendered as HTML. :javascript alert('foo'); The script tag will be output exactly where you put it in the view.
In Haml, we write a tag by using the percent sign and then the name of the tag. This works for %strong , %div , %body , %html ; any tag you want. Then, after the name of the tag is = , which tells Haml to evaluate Ruby code to the right and then print out the return value as the contents of the tag.
What is it? Haml (HTML abstraction markup language) is based on one primary principle: markup should be beautiful. It's not just beauty for beauty's sake either; Haml accelerates and simplifies template creation down to veritable haiku.
Inline small CSS should be included within the <head> tags of an HTML file while inline small JavaScript can be included either within the <head> tag or the <body> tag. In most cases, using an external file to call your CSS and JavaScript is considered best practice.
You don't need the script's type
attribute, and you can use the html syntax
%script(src="/js/myscript.js")
you could always create a "helper" to generate it if you feel like it
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With