I was wondering if someone can tell me about how Ruby code can get integrated with HTML and CSS code like Javascript does? Javascript has syntax for manipulating HTML elements, is this possible with Ruby? I searched online and see that there is a .erb file that can be used. It is very confusing though so was hoping someone can shed some light on this for me. Thanks!
-
1I suspect you are confused about where Ruby code can be interpreted. I'm not aware of any browsers that include Ruby interpreters (unlike JavaScript interpreters). – Derrell Durrett Jul 08 '16 at 14:54
-
This question is two questions in one. The first question (how Ruby gets integrated with HTML and CSS) is indeed answered by the nominated exemplar. The second one (can Ruby manipulate HTML elements as Javascript does?) is not. I'll close this as a duplicate (the other choice would be to close it as "too broad". I recommend that the second question be asked by itself, if it hasn't been already. – Wayne Conrad Jul 08 '16 at 16:39
1 Answers
Ruby uses erb or embedded ruby to manipulate html. You see that your view files ends with .html.erb.
In those files, you can write ruby inside the html file. For example:
<% if condition %>
<p> This condition is true </p>
<% end %>
That being said, if you view on page on a browser and looks at the source code, you will not see any ruby codes. The code is interpreted and html is generated when the user views the page.
Ruby uses Rails as its framework. Rails use the Model-View-Controller format. A lot of the logic behind a Ruby on Rails application is put into the controller.
I will provide an example of how to potentially manipulate html and css in ruby.
In your css file, let's say you have
.modify {
background-color: blue;
}
In your index.html.erb file,
<p class= @manipulate> Some content </p>
The @manipulate
is an instance variable, you can click this link to learn more about instance variables.
Then, in your controller file, you have an index method, which corresponds to the index.html.erb file.
def index if condition == true @manipulate = 'modify' else @manipulate = '' end end
So, based on certain conditions set, the controller will return a value for @manipulate, which is interpreted in the index.html.erb file. If you make the condition true, and view the page from a browser, you will see in the source code that the class for the
tag is now modify.
I hope this helps.

- 9,523
- 6
- 32
- 53