How to include inline JavaScript in HAML ?
Last Updated :
03 Jun, 2020
Improve
There are mainly two ways to include JavaScript in HTML:
HTML
Output:
In HAML, instead of using the "script" tag,
html
Output:
Another way of including inline JavaScript into HAML is by the use of
html
Output:
Reference: http://haml.info/docs/yardoc/file.REFERENCE.html#javascript-filter
- Internal/Inline: By using "script" element in the "head" or "body" section.
- External: By using an external JavaScript file.
<!DOCTYPE html>
<html>
<head>
<title>HTML inline JavaScript demo</title>
</head>
<body>
<div id="container">
<p>Hi, no script applied yet!</p>
</div>
<script type="text/javascript">
var tag = document.createElement("p");
var text = document.createTextNode(
"Inline JavaScript is applied!");
tag.appendChild(text);
var element = document.getElementById("container");
element.appendChild(tag);
</script>
</body>
</html>

:javascript
could be used. Take care of the indentations because HAML is indentation sensitive.
:javascript // JavaScript code goes here with proper indentationSo, the same initial HTML example in HAML becomes:
%html
%head
%title Basic Haml Template
%body
%div#container
%p Hi, no script applied yet!
:javascript
var tag = document.createElement("p");
var text = document.createTextNode(
"Inline JavaScript is applied!");
tag.appendChild(text);
var element = document.getElementById("container");
element.appendChild(tag);

%script{type: "text/javascript"}
%script{type: "text/javascript"} // JavaScript code goes here with proper indentationThis format is useful when you would want to use a different type than
text/javascript
.
The initial example in HAML with the use of this method to include inline JavaScript:
%html
%head
%title Basic Haml Template
%body
%div#container
%p Hi, no script applied yet!
%script{type: "text/javascript"}
var tag = document.createElement("p");
var text = document.createTextNode(
"Inline JavaScript is applied!");
tag.appendChild(text);
var element = document.getElementById("container");
element.appendChild(tag);
