Entering variable values ​​in javascript and HAML in RoR

I have the following function to use ZenDesk. I would like to add my current_user data to the form as follows. (this is my html.haml template). However, I cannot figure out how to do this.

:javascript if (typeof(Zenbox) !== "undefined") { Zenbox.init({ dropboxID: "xxxxx", url: "xxxxx.zendesk.com", tabID: "support", tabColor: "black", tabPosition: "Left", requester_name: =current_user ? "#{current_user.first_name} #{current_user.last_name}" : "" , requester_email: =current_user ? "#{current_user.email}" : "" , hide_tab: true }); } 

In short, how one inserts rail variables into an element: javascript in haml.

+45
javascript ruby-on-rails haml
Jan 16 '11 at 10:01
source share
2 answers

This should work, i.e. put all the built-in ruby ​​inside #{} :

 requester_name: "#{current_user.first_name + ' ' + current_user.last_name if current_user}", requester_email: "#{current_user.email if current_user}", 
+54
Jan 16 2018-11-22T00:
source share

Direct #{} works for simple strings, but is not the most scalable / secure solution in general.

For example, a literal backslash in Ruby will cause problems in Javascript, where it will be interpreted as a newline:

 - a = "\\n" :javascript '#{ a }' !== "\\n" 

From this amazing Rails cast you can use the following methods:

escape_javascript

Alias: j .

Only works with strings.

Resets characters that may have special meanings in Javascript strings, such as escape backslashes, to a format suitable for inputting literals in Javascript.

Maintain html_safe input status, therefore html_safe is required otherwise special HTML characters such as < will be escaped to &lt; .

 - a = "\\n<" :javascript '#{ j(a) }' === '\\n&lt;' '#{ j(a).html_safe }' === '\\n<' 

to_json + html_safe

This works because JSON is almost a subset of the literal notation of Javascript objects .

It works on any hash object, including strings, arrays and integers, which are converted to JSON fragments of the corresponding data type.

 - data = { key1: 'val1', key2: 'val2' } :javascript data = #{ data.to_json } data.key1 === 'val1' data.key2 === 'val2' 

data attributes

Add values ​​to attributes, retrieve them using Javascript DOM operations.

Better with content_tag helper:

 = content_tag 'div', '', id: 'data', data: {key1: 'val1', key2: 'val2'} :javascript $('#data').data('key1') === 'val1' $('#data').data('key2') === 'val2' 

square

Task-specific library: https://github.com/gazay/gon

Perhaps the most reliable solution.

Gemfile:

 gem 'gon' 

Controller:

 gon.key1 = 'val1' gon.key2 = 'val2' 

Layout app/views/layouts/application.html.erb :

 <html> <head> <meta charset="utf-8"/> <%= include_gon %> 

View:

 :javascript gon.key1 === 'val1' gon.key2 === 'val2' 
+20
Jun 27 '14 at 16:23
source share



All Articles