1

I would like to move some js inline scripts I have on my homepage to a javascript file (in Assets) but there is some complexity due to variables.

home.html.erb

<div>
this is the homepage
</div>
<script>
  <% @deal.deal_details.each_with_index do |popin, index| %>
  <% index_plus_one = index + 1 %> 
    function loadInfoPopin() {
      var msg;
      msg = Messenger().post({
        message:  '<%= j render partial: "deals/info_popin/info_popin#{ popin['popin_id'] }",
                  locals: { popin: popin, index: index_plus_one } %>'
      });
    } 
  <% end %>
</script>

For the sake of information here is the format of the Deal's column/attribute 'deal_details' (it's a json attribute):

[{"popin_id":"4","text1":"qqq","text2":"sqsq","image1":"sqqs"},{"popin_id":"5","text1":"sqqs","video1":"s"}] 

This is an example and you can have as many json block inside the array as possible.

deals/info_popin/info_popin5.html.erb (it's an example)

<div>
       <p><a href="<%= popin['image1'] %>">cool image</a></p>
    </div>
</div> 

Now, how can I move the whole script or at least the function loadInfoPopin() to a javascript file (that is to say away from the view home.html.erb) ?

Thanks

2 Answers 2

1

How about moving the loadInfoPopin() function into a separate JS file and altering the function slightly to take in an argument for the html message?

function loadInfoPopin(html_message) {
  Messenger().post({
    message:  html_message
  });

Setup the html for the message within the loop before passing into and calling loadInfoPopin.

Sign up to request clarification or add additional context in comments.

Comments

0

.js.erb is an option. This way the js files will be parsed before compiling. Not sure though it will work the way you want.

I would recommend to leave the variables in the layout as vars and moving only the static JS parts to the assets.

1 Comment

I alreayd tried with gon gem and using a .js.erb file but it does not work. I 'd need more precise code suggestion.

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.