简体   繁体   中英

How to use JavaScript variable in Haml?

I have a javascript function (available on all pages as it's included in application.js) that detects if the browser has Flash support and outputs true or false.

Now, I want to show a flash based price chart if true and a HTML/Javascript based chart if false.

At the top of a Haml page I try to pass the result of the javascript function to HAML like this:

:javascript
  if (browserHasFlashSupport())
    #{showFlashChart = true}

And use it in Haml further down on the page like this:

- if showFlashChart
    # show flash chart
- else
    # show html/js chart

But I can't get it to work as the ruby variable showFlashChart is "true" no matter what - but in console, the javascript function browserHasFlashSupport() returns true/false like it should, so I must be doing something wrong.

I guess it would probably be the best solution just to use the javascript functions "return true/false" directly in HAML like - if browserHasFlashSupport() if that's possible and the "right" way to do it?

I'd appreciate any help, thanks :-)

PS. Any tips on how to avoid the usage of inline javascript in my HAML file would be very welcome too.

The problem of your solution:

Your javascript function has to be run in a client's browser to detect if it has flash support.

Here is what happens when a user wants to get a page from your site:

  1. User's browser sends request to your server.
  2. Your server handles the request, compiles views(eg HAML) . Also rails adds <script> tags to the output html page. These tags will contain urls to your scripts (defined in application.js or others). Then the server responds with this html page.
  3. User's browser loads compiled page from your sever.
  4. The browser sees the <script> tags and automatically downloads javascript sources from specified urls.
  5. And only now in the clients browser your javascript functions may be run .

You see that your haml template was rendered on the step 2 and your javascript function may be run only on step 5.

That is a lot simplified case. But it is impossible to make step 5 to precede step 2 (without use of ajax or cookies). That is why your way is impossible.

Hope this is quite descriptive.

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