Syntax error when including HTML tags in Draper + create.js.erb

Rails 5.2.3 ruby 2.6.6

I wrote a solution because I couldn't draw a decorator containing HTML tags in * .js.erb.

Solutions

JQuery in create.js.erb uses single quotes.

javascript:create.js.erb


// OK
$("#tag").html('<%= @model.start_btn %>')

// NG
$("#tag").html("<%= @model.start_btn %>")

Cause

Double quotes are not escaped.

The following error.

missing ) after argument list


    at processResponse (rails-ujs.source.js:272)
    at rails-ujs.source.js:200
    at XMLHttpRequest.xhr.onreadystatechange (rails-ujs.source.js:255)

If you check the last line on the console,

> xhr.response

"$("#ajax-response-message").html("")
$("#ajax-response-message").removeClass().addClass("alert alert-info")
$("#ajax-response-message").html("Error message")

$("#btn-area").html("<button type="submit" class="btn btn-danger" id="start"><i class="fas fa-check-circle"></i> <span>start</span></button>")"
↑↑↑ Not escaped! !!

Conclusion

It's not a good idea to assume that you're escaped.

Recommended Posts

Syntax error when including HTML tags in Draper + create.js.erb
Error in bundle install when running rails new
[Rails] Solution when migration error occurs in acts-as-taggable-on