我有一个部分需要一些相关的脚本,所以我想在使用部分时将这些javascript include标签附加到标题中。所以我做了:
# 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次。 如何仅将脚本附加一次?
答案 0 :(得分: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