[英]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. 我有一个javascript函数(在application.js中包含在所有页面上),该函数可检测浏览器是否具有Flash支持并输出true或false。
Now, I want to show a flash based price chart if true and a HTML/Javascript based chart if false. 现在,我想显示一个基于Flash的价格图表(如果为true),以及一个基于HTML / Javascript的图表(如果为false)。
At the top of a Haml page I try to pass the result of the javascript function to HAML like this: 在Haml页面的顶部,我尝试将javascript函数的结果传递给HAML,如下所示:
:javascript
if (browserHasFlashSupport())
#{showFlashChart = true}
And use it in Haml further down on the page like this: 并像下面这样在页面的更下方的Haml中使用它:
- 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. 但是无论如何,我都无法使用它作为ruby变量showFlashChart为“ true”-但是在控制台中,javascript函数browserHasFlashSupport()像应该的那样返回true / false,因此我必须做错了事。
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? 我猜想直接在HAML中使用javascript函数“返回true / false”可能是最好的解决方案,例如
- if browserHasFlashSupport()
可行的话,以及“正确”的方法呢?
I'd appreciate any help, thanks :-) 我将不胜感激,谢谢:-)
PS. PS。 Any tips on how to avoid the usage of inline javascript in my HAML file would be very welcome too.
也将非常欢迎您提供任何有关如何避免在HAML文件中使用内联javascript的提示。
The problem of your solution: 您的解决方案的问题:
Your javascript function has to be run in a client's browser to detect if it has flash support. 您的javascript函数必须在客户端的浏览器中运行,以检测其是否具有Flash支持。
Here is what happens when a user wants to get a page from your site: 当用户想要从您的网站获取页面时,将发生以下情况:
<script>
tags to the output html page. <script>
标记添加到输出html页面。 These tags will contain urls to your scripts (defined in application.js
or others). application.js
或其他文件中定义)。 Then the server responds with this html page. <script>
tags and automatically downloads javascript sources from specified urls. <script>
标记,并自动从指定的URL下载javascript源。 You see that your haml template was rendered on the step 2 and your javascript function may be run only on step 5. 您会看到您的haml模板是在步骤2上呈现的,并且您的javascript函数可能仅在步骤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).
但是不可能将步骤5置于步骤2之前(不使用Ajax或cookie)。 That is why your way is impossible.
这就是为什么你的方法是不可能的。
Hope this is quite descriptive. 希望这是描述性的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.