简体   繁体   中英

Embedding rails erb in javascript

Inside of a view in my rails app. I am trying to detect the screen size using JavaScript and render some rails content depending on the screen size.

Here is what I have:

<script>
if( $(window).width() < 1000){
'<%= @resize = true %>';
} else {
'<%= @resize = false %>';
}
</script> 

I keep getting false returned for the @resize variable even if the browser window size is less than 1000. How would I go about getting this to work?

You need to change things up:

  1. Write JS that sets a cookie containing the value you want based on the conditions.
  2. Read the value of that cookie in Rails.

Note the problem with this approach is that on the very first page load Rails won't have access to that cookie data. Only on the next request will it get the value. But there's no way around that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM