how to run ruby in haml in javascript definition?
First, let's review what you seem to know:
- Ruby requires you to define local variables before you use them.
- You can run Ruby code on lines outside of a filter using
- ...
. - You use
#{...}
markup to interpolate Ruby code inside a filter.
You say you want to run each
, but presumably you want output from this; since the result of #{...}
is turned into a string and put in your code, what you really want (probably) is map
:
%html
%head
:javascript
var foo = [];
#{
limit = rand(4)+3
array = (0..limit).to_a
array.map{ |i| "foo[#{i}] = #{rand(12)};" }.join ' '
}
console.log(foo.length);
%body
Running the above code gives this output:
<html>
<head>
<script type='text/javascript'>
//<![CDATA[
var foo = [];
foo[0] = 2; foo[1] = 0; foo[2] = 11; foo[3] = 8; foo[4] = 0; foo[5] = 1;
//]]>
</script>
<body></body>
</head>
</html>
As you can see, the big #{...}
block (which may span multiple lines) runs arbitrary Ruby code. The result of the last expression (in this case the map{...}.join
) is converted to a string and placed in the output.
Ruby methods within Javascript within HAML
Usually, if something is a pain in haml, it means you should refactor the the tricky bit to a helper or partial and call that.
// some_helper.rb
def new_snazzy_select_tag(options = [])
select_tag 'tag_name_here', options.map { |option| [option.id, option.name] }
end
Also, you should use the :javascript
filter to render javascript since it will put it in a script tag for you and allow indentation.
Lastly, you can use #{ruby_expression}
anywhere in haml, including :javascript
filters, which is very handy when you need to output the result of ruby expressions to places that are not directly contents of html elements.
// some_view.html.haml
:javascript
$('#mylink').click(function() {
$('#mylink').after("#{escape_javascript new_snazzy_select_tag(myarray)}");
};
Javascript in HAML in Javascript
You have two options.
- You can use AJAX request to get data from database
You can use mapping concept like following
var data = @processed_data // json data, which contains processed data in json format.
var accu_id = $("#accu")[0].selectedOptions[0].value
var price = data.accu_id;
Here the @processed_data contains data like following
@processed_data = currency_calculation
def currency_calculation
Product.all.map { |product| [product.id, currency(product.price2) ] }.as_json
end
Example
Assume products table have two entries then the @processed_data contain values like following
{ "1" => "20.00", "2" => "25.50" }
The above data directly assigned to js variable data and accessed like data.key
The first option is best choice and second is possible one.
Note : You can't use js variable inside ruby.
How to define ruby code inside a haml file present in javascript folder
Disclaimer: I'm bad at Angular (and didn't even touch version 2). What follows is not a best practice or anything.
So, you need to configure your angular view with some knowledge from ruby side. You can't conditionally render it and you can't call ruby from angular controllers (obviously). I suggest smuggling data via window
object.
In an appropriate view in your application, put this JS snippet.
<script type='text/javascript'>
window.jsEnv = {
hide_hours_field: <%= ABC::D.data[:hide_hours_field] %>
}
</script>
Then you can reference that via $window
object in angular
Controller
function MyController($window) {
this.hideHours = function() {
return !!$window.jsEnv.hide_hours_field;
}
}
MyController.$inject = ['$window'];
angular.module('myApp').controller('MyController', MyController);
View
.small-12.columns(ng-controller='MyController as vm')
.booking-time
%span.bold(ng-if='vm.hideHours()')
{{ item | timeformat }}
%span.bold(ng-unless='vm.hideHours()')
{{ item | differentTimeFormat }}
How can I use a Ruby variable in an inline JavaScript in haml?
You can use the simple "#{}" interpolation tags to use ruby variables with HAML.
Your code:
:javascript
alert(<%=raw @status %>)
Possible Solution:
:javascript
alert("#{@status}")
Is there a way to use a Ruby loop inside of HAML's :javascript region?
this one works
%script
- 10.upto(20) do |i|
document.getElementById('aDiv').innerHTML += '#{i}';
How to use JavaScript variable in Haml?
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:
- User's browser sends request to your server.
- Your server handles the request, compiles views(e.g. HAML).
Also rails adds<script>
tags to the output html page. These tags will contain urls to your scripts (defined inapplication.js
or others). Then the server responds with this html page. - User's browser loads compiled page from your sever.
- The browser sees the
<script>
tags and automatically downloads javascript sources from specified urls. - 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.
Injecting variable values into javascript and HAML in RoR
This should work ie. put all inline ruby inside of #{}
:
requester_name: "#{current_user.first_name + ' ' + current_user.last_name if current_user}",
requester_email: "#{current_user.email if current_user}",
Call a ruby array in external javascript from Haml
You can print the variable like this in HAML
%script
!= "close_array_j = #{@close_array.to_json};"
and then use it in javascript
...
series: [{
name: 'Closing Price',
data: close_array_j
}]
...
Related Topics
Add Current Time Before Log Message
Trying to Get Svn2Git Working on Windows
How to Change Case of Letters in String Using Regex in Ruby
Ruby String Strip Defined Characters
Rake: Logging Any Task Executing
Naming Conventions for Boolean Attributes
Get Available Diskspace in Ruby
Why Array.Reverse_Each Is Faster Than Array.Reverse.Each
Have a Parent Class's Method Access the Subclass's Constants
Converting Time in Utc to Pacific Time
How to Make Single Digit Number a Two Digit Number in Ruby
Form_For with Multiple Controller Actions for Submit
Fast Fuzzy/Approximate Search in Dictionary of Strings in Ruby