[英]Moving Rails yield into a helper file
我正在渲染這樣的標題標簽(我正在使用meta-tags gem):
about.html
= content_for :page_title, 'About page'
application.html
%title
= yield(:page_title)
但是我想將yield移到一個輔助文件中,所以它將像這樣工作:
about.html
= title_tag_generator("About page")
title_helper.rb
def title_tag_generator(page_title)
content_tag :title do
yield(page_title)
end
end
我一直沒有得到任何限制(產量)。 有什么建議嗎?
遵循捕獲助手指南
但是,content_for也可以在幫助程序模塊中使用。
module YourViewHelper
def title_tag_generator
# Your complex code that I believe generates lot of HTML
# And which can use content_for(:title) here
end
end
然后,您可以在視圖中調用title_tag_generator
。
當您在視圖中調用title_tag_generator
,並沒有給出阻止。 當您的輔助方法到達yield
調用時,它什么也做不了,並給您一個很好的錯誤消息。 對於yield語句,確實沒有給出任何阻止。
您可以對此進行編碼,然后使用block_given?
檢查是否有一個要屈服的塊block_given?
:
def title_tag_generator(page_title)
content_tag :title do
if block_given?
yield(page_title)
end
end
end
然后,如果有一個區塊,您將屈服於一個區塊;如果沒有區塊,您將快樂地進行。
要使用一個塊調用您的輔助方法,您可以選擇執行以下操作:
title_tag_generator('My Page') do |page_title|
"My title is: " + page_title
end
或在HAML中:
- title_tag_generator('My page') do |page_title|
%strong= page_title
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.