Skip to content Skip to sidebar Skip to footer

Create Method In Html.erb File

I have to create one method in file say 'myCode.html.erb'. I have to write ruby code with html. So far I came to know how to write method and call that method as below. method crea

Solution 1:

Use helper method . Use rails DRY principle.

Just write Method in ApplicationHelper Module.

Example:

moduleApplicationHelperdefhalo"This is function"endend

Solution 2:

It is not likely what you really want to do. But you can do it.

<% 
def hello
  'Hello World'
end
%>

<p>This is simply an erb file (really just a text file)</p><p><%= hello %></p>

Solution 3:

Define method in some Helper

moduleTestHelperdeftestreturn'Hello World'endend

In your HTML file / .erb, you just insert

<%= TestHelper.test %>

In your HTML you will see 'Hello World'

Solution 4:

A correct way to do that is to define a partial that can consume parameters.

To achieve that, you render your partial from the calling view with:

<%= render partial: "my_partial", locals: {variable: "my value", other_variable: "other value"} %>

In the partial, you just render the value of the variables where you need them with:

<%= variable %>

For example,

<span>Variable has value <%= variable %>, while the other variable has value <%= other_variable %>.</span>

Post a Comment for "Create Method In Html.erb File"