2009-11-08 99 views
0

我發現自己經常寫這樣的代碼在HTML HEAD和其他地方:有條件地在視圖中顯示信息的更好方法?

<% if @canonical_url %> 
    <link rel="canonical" href="<%= @canonical_url %>"/> 
<% end %> 

然後我設置變量的控制,如果是適當的。

有沒有什麼方法可以在同一行上編寫等價物,或者用不同的方式來組織代碼?

回答

1

好的,我想出了這個解決方案。在模板:

<%= show_if('<link rel="canonical" href="$1"/>', @canonical_url) %> 

然後輔助方法:

# 
# Return the template text if the variable has a value. 
# 
def show_if(template, variable) 
    if variable 
    template.gsub('$1', variable) 
    else 
    '' 
    end 
end 
1

我需要多一點的環境來確定它是什麼,你想要做的事。鑑於您提供的信息,我建議您查看canonical-url plugin for Rails

0
def if_value(value, &block) 
    if value 
    concat(capture(value, &block)) 
    end 
end 

<% if_value(@canonical_url) do |value| %> 
    <link rel="canonical" href="<%= value %>"/> 
<% end %> 
2

對不起,雙重答案,SO只會讓我發佈一個網址。

或者,您的問題可能通過使用content_for in your views來解決,您希望將此內容顯示在您的佈局中。

相關問題