[英]Ruby erb template 'or' operator
我有一個使用erb模板的p清單。
根據文檔,這是正確的語法,並且效果很好。
<% if foo != bar %>
derp
<% else %>
herp
<% end %>
如何將if語句與“或”運算符組合?
這是我嘗試過的以下語法,但是它們返回錯誤:
<% if foo != bar or if slurp != burp %>
derp
<% else %>
herp
<% end %>
Error: Could not run: /etc/puppet/modules/gitlab/templates/gitlab.yml.6-7-stable.erb:275: syntax error, unexpected $end, expecting keyword_end
; _erbout.force_encoding(__ENCODING__)
<%% if foo != bar or if slurp != burp %%>
derp
<% else %>
herp
<% end %>
Error: Could not run: /etc/puppet/modules/gitlab/templates/gitlab.yml.6-7-stable.erb:241: syntax error, unexpected keyword_else, expecting $end
; else ; _erbout.concat "\n derp "
^
我試過分裂if-s
<% if foo != bar %> or <% if slurp != burp %>
derp
<% else %>
herp
<% end %>
Error: Could not run: /etc/puppet/modules/gitlab/templates/gitlab.yml.6-7-stable.erb:275: syntax error, unexpected $end, expecting keyword_end
; _erbout.force_encoding(__ENCODING__)
^
if
有一個額外的。 正確的語法是:
<% if foo != bar or slurp != burp %>
derp
<% else %>
herp
<% end %>
但是, if-else
您的if-else
構造錯誤, if-else
您的組件將無法工作。 閱讀if-else
構造的文檔。
if / else塊的Ruby語法為:
如果有條件
條件可以包括任何邏輯運算符,例如'or','and','&','|','&&','||'。
但是,它不能包含另一個if塊,因為您的示例具有:
如果foo!= bar或if飲!=打p
ERB 是 Ruby 1 。 ERB只需將標記中的Ruby和“內聯文本”提取為代碼和行內字符串/輸出構建的混搭,即可生成中間Ruby,然后將其執行。
因此,提取實際的Ruby (由ERB執行)如下所示:
if foo != bar or if slurp != burp
# some inconsequential ERB magic to output "derp"
else
# some inconsequential ERB magic to output "herp"
end
現在,用偽表達式填充不感興趣的部分將產生以下結果。 (忽略字符串始終是true表達式;問題是語法錯誤 。)
if "hello" or if "world"
else
end
並產生預期的錯誤消息(請參閱ideone演示 )。
prog.rb:3:語法錯誤,意外的$ end
那么.. 為什么呢?
這是因為有兩個 if
-expressions 2 ,但是僅關閉了一個 -expressions 2 ,並且已對代碼進行了解析,就像添加了分組括號一樣。
if "hello" or (if "world"
else
end) # <-- no `end` for `if "hello"`!
解決方法是再簡單地刪除嵌套if
-expression。
# no extra `if` here, so only looking for one `end` below
if "hello" or "world"
else
end
1更正確的說法是ERB標簽中的代碼是 Ruby,而ERB直接使用ERB標簽的內容在內部生成 Ruby。 這與其他模板引擎不同,后者引入了自己的語法和解析器。 ERB 是 Ruby。
2 expr if expr
(以及if expr then .. end
)形式,Ruby也支持expr if expr
。 無論如何,基本問題是添加第二個不必要的if
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.