[英]Create method in html.erb file
我必须在文件中创建一个说'myCode.html.erb'的方法。 我必须用html编写ruby代码。 到目前为止,我开始知道如何编写方法并调用该方法,如下所示。
method creation
<%def helo
print "This is function"
end%>
<%=helo%> #calling method
但是我在如何编写我必须编写ruby和html代码的方法时陷入困境。 下面是我需要在方法中编写的代码。
<%
actions.each{ |action|
tc = []
bizA = []
testcaseName = ''
bizActionName = ''
@factory.testcases.rows({'steps.action._actionId' => action["_id"]}).each{|testcase|
d = ''
testcaseName = testcase['attributes']['name'] + d
d = ', '
tc << testcaseName
}
# require 'ruby-debug' ; debugger
if !action['isGrouping']
actions.each{|act|
if act['isGrouping']
temp = []
temp = act['steps']
temp.each{|step|
if action['_id']==step['action']['_actionId']
bizA << act['name']
end
}
end
}
end
%>
<tr>
<td><%= name %></td>
<td><%= action['name'] %></td>
<td><%= @factory.testcases.rows({'steps.action._actionId' => action["_id"]}).length %> </td>
<td>
<% counter=1%>
<% for ix in 0..tc.length-1 %>
<% if counter%2==0 %>
<%if ix!=tc.length-1 %>
<font color="black"><%= tc[ix] %></font> <br/>
<%else%>
<font color="black"><%= tc[ix] %></font> <br/>
<%end%>
<% else %>
<%if ix!=tc.length-1 %>
<font color="brown"><%= tc[ix] %></font> <br/>
<%else%>
<font color="brown"><%= tc[ix] %></font> <br/>
<%end%>
<%end%>
<% counter=counter+1 end %>
</td>
<td><%=bizA.length%></td>
<td>
<% counter=1%>
<% for ix in 0..bizA.length-1 %>
<% if counter%2==0 %>
<%if ix!=bizA.length-1 %>
<font color="black"><%= bizA[ix] %></font> <br/>
<%else%>
<font color="black"><%= bizA[ix] %></font> <br/>
<%end%>
<% else %>
<%if ix!=bizA.length-1 %>
<font color="brown"><%= bizA[ix] %></font> <br/>
<%else%>
<font color="brown"><%= bizA[ix] %></font> <br/>
<%end%>
<%end%>
<% counter=counter+1 end %>
</td>
</tr>
<% } %>
如果我将上面创建的方法helo
作为参考并以这种方式编写这个ruby + html代码,它就不起作用了。 它显示语法错误。
使用辅助方法。 使用rails DRY原理。
只需在ApplicationHelper模块中编写Method即可。
例:
module ApplicationHelper
def halo
"This is function"
end
end
这不太可能是你真正想要做的。 但你可以做到。
<%
def hello
'Hello World'
end
%>
<p>This is simply an erb file (really just a text file)</p>
<p><%= hello %></p>
在某个Helper中定义方法
module TestHelper
def test
return 'Hello World'
end
end
在您的HTML文件/ .erb中,您只需插入即可
<%= TestHelper.test %>
在您的HTML中,您将看到“Hello World”
正确的方法是定义可以使用参数的部分。
为此,您可以使用以下命令从调用视图中呈现部分:
<%= render partial: "my_partial", locals: {variable: "my value", other_variable: "other value"} %>
在partial中,您只需使用以下内容渲染变量的值:
<%= variable %>
例如,
<span>Variable has value <%= variable %>, while the other variable has value <%= other_variable %>.</span>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.