2

I have a partial that requires some related script, so I want to append those javascript include tags to the header whenever the partial is used. So I did:

# 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'

Which of course causes the javascript tag to be appended 3 times and therefore to run alert("I've been required!!") 3 times. How to append the script only once?

1 Answer 1

1

This problem came to me, so I decided to share the solution here. It's not a problem of high complexity but may spare you the half an hour it took me...:

- 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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.