coffeescript - Dynamically insert ruby generated HTML -
i have form user can elect create more input areas (to provide more information). have link user click on , form inputs created. i'd use rails form helpers don't have write html myself. i've tried inserting form helpers directly coffeescript , saving outputted html data tag on link, can't coffeescript execute ruby code , i'm having escaping issues data attribute.
here's form:
= simple_form_for([@site, @zone]) |f| = f.error_notification .form-inputs = f.input :site_id = label_tag "x" = text_field_tag 'x_coords[]' = label_tag "y" = text_field_tag 'y_coords[]' = label_tag "x" = text_field_tag 'x_coords[]' = label_tag "y" = text_field_tag 'y_coords[]' = label_tag "x" = text_field_tag 'x_coords[]' = label_tag "y" = text_field_tag 'y_coords[]' = link_to "add point", "#", id: "add_point", data: { fields: label_tags } .form-actions = f.button :submit
when user clicks "add point" link, i'd add block of:
= label_tag "x" = text_field_tag 'x_coords[]' = label_tag "y" = text_field_tag 'y_coords[]'
label_tags
in application_helper.rb
:
def label_tags label_tag "z" end
the problem output "add point" link is:
<a href="#" data-fields="<label for=" z"="">z" id="add_point">add point</a>
and quotation marks causing link come out text: "z" id="add_point">add point"
i got data attribute idea screencast
you cannot execute ruby code javascript. when page requested embedded ruby evaluated , results get. issue can see paste label block in right data attribute it's not escaped.
what you'll need escape quotes on generated html going field , unescape them via javascript. use html_escape
here like: data: { fields: h(label_tags) }
(h
alias html_escape
or yourself, manually.
def escape(str) str.gsub(/</, "<").gsub(/>/, ">").gsub(/"/, """) end # later in view form data: { fields: escape(label_tags) }
and coffeescript click handler like:
function unescape(str) { return str.replace(/((?:<)|(?:>)|(?:"))/g, function($1) { switch($1) { case ">": return ">"; case "<": return "<"; case """: return '"'; } }); } $("a").on("click", function() { var html = unescape(this.data("fields")); $(".the-place-to-put-it").html(html); });
i not doubt better solution exists , of posting of answer have not tested work (in theory should). ideally, should generate elements jquery in javascript , not depend on method doing - yes, it's duplicate code duplicated between ruby , coffee.
Comments
Post a Comment