2014-10-28 55 views
2

我有一個部分需要一些相關的腳本,所以我想要追加這些JavaScript包含標籤的頭部,每當部分使用。所以我做:Rails部分︰使用content_for追加JavaScript包含標籤只有一次

# app/assets/javascripts/tricky_js.js.coffee 
alert "I've been required!!" 

# app/views/layouts/application.slim 
head 
    # stuff... 
    = yield :head 

body 
    = yield 

# app/views/shared/_tricky_partial.slim 
content_for :head do 
    = javascript_include_tag :tricky_js 

p Bleh 

# app/views/shared/unrelated_view.slim 
= render 'shared/tricky_partial' 
= render 'shared/tricky_partial' 
= render 'shared/tricky_partial' 

這當然會導致JavaScript代碼來追加3倍,因此運行alert("I've been required!!") 3倍。 如何追加腳本一次?

回答

1

這個問題來找我,所以我決定在這裏分享解決方案。這不是一個複雜度高的問題,但可能會讓你花費我半小時的時間...:

- unless content_for? :tricky_partial_assets 
    - content_for :tricky_partial_assets do 
    = stylesheet_link_tag :columns 
    = stylesheet_link_tag :feedback_table 
    /* v here is (almost) all the JS powering this partial */ 
    = javascript_include_tag :feedback_table 
    = javascript_include_tag :wish_list_items 

/* Append only once */ 
- unless content_for? :tricky_partial_assets_provided 
    - content_for :head, content_for(:tricky_partial_assets) 
    - content_for :tricky_partial_assets_provided, true 
相關問題