我们尝试做的是将erb
代码块存储在string
中,然后在运行时执行代码。这是我们做的一个测试:
1.从工作的erb文件中取出代码块,
1.用val重写erb文件。
以下是取出的ERB代码块:
<tr>
<th>#</th>
<th><%= t('Date') %></th>
<th><%= t('Project Name') %></th>
<th><%= t('Task Name') %></th>
<th><%= t('Log') %></th>
<th><%= t('Entered By') %></th>
</tr>
<% @logs.each do |r| %>
<tr>
<td><%= r.id %></td>
<td><%= (r.created_at + 8.hours).strftime("%Y/%m/%d")%></td>
<td><%= prt(r, 'task.project.name') %></td>
<td><%= prt(r, 'task.task_template.task_definition.name') %></td>
<td><%= prt(r, :log) %></td>
<td><%= prt(r, 'last_updated_by.name') %></td>
</tr>
<% end %>
t()
是国际化的翻译方法。
以下是重写后的erb文件:
<table class="table table-striped">
<% code = find_config_const('task_log_view', 'projectx')%>
<%= eval(code)%>
</table>
在重写之前,代码块位于<table>
之间。现在,变量code
返回代码块的string
,eval
执行代码块。但这里有一个错误:
(eval):1: syntax error, unexpected '<'
(eval):4: syntax error, unexpected tIDENTIFIER, expecting $end
<th><%= t('Project Name') %></th>
^
Extracted source (around line #6):
4: <table class="table table-striped">
5: <% code = find_config_const('task_log_view', 'projectx')%>
6: <%= eval(code)%>
7:
8: </table>
9:
上面的代码有什么问题?
1条答案
按热度按时间ljo96ir51#
eval
通过评估Ruby代码来工作。转换ERB模板时应使用
ERB
类完成我猜测
code
实际上是一个包含ERB模板而不是Ruby代码的字符串。尽管如此,我不认为这是一个好方法。
task.project.name
可能来自数据库,可能来自用户输入。在这上面做评估似乎不是一个好主意。也许你可以用普通的
partials
解决你的问题。