javascript_tag(content_or_options_with_block = nil, html_options = {}, &block) public

Returns a JavaScript tag with the content inside. Example:

javascript_tag "alert('All is good')"

Returns:

<script>
//<![CDATA[
alert('All is good')
//]]>
</script>

html_options may be a hash of attributes for the <script> tag.

javascript_tag "alert('All is good')", defer: 'defer'

Returns:

<script defer="defer">
//<![CDATA[
alert('All is good')
//]]>
</script>

Instead of passing the content as an argument, you can also use a block in which case, you pass your html_options as the first parameter.

<%= javascript_tag defer: 'defer' do -%>
  alert('All is good')
<% end -%>

If you have a content security policy enabled then you can add an automatic nonce value by passing +nonce: true+ as part of html_options. Example:

<%= javascript_tag nonce: true do -%>
  alert('All is good')
<% end -%>
Show source
Register or log in to add new notes.