Search code examples
htmlcssruby-on-railstwitter-bootstrapglyphicons

How to use Twitter Bootstrap's glyphicons with Rails's button_to


I have a couple buttons that submit AJAX requests.

<%= button_to 'GO!', {controller:'videos', action:'rate', id: video.hashed_id, format: 'json'}, {:remote=>true, :class=>"btn btn-default btn-sm"} %>

If I replace GO! with <span class="glyphicaon glyphicon-thumbs-up"></span> it ends up causing this value="<span class="glyphicaon glyphicon-thumbs-up"></span>"

Any ideas how I can get a glyphicon into a button that submits a form?

Update

I tried this:

<%= button_to content_tag(:i, '', class: 'icon-thumbs-up'), {controller:'videos', action:'rate', id: video.hashed_id, format: 'json'}, {:remote=>true, :class=>"btn btn-default btn-sm"} %>

which created this:

<form action="/videos/rate/asdfsxsdf/no.json" class="button_to" data-remote="true" method="post">
<div><input class="btn btn-default btn-sm" type="submit" value="<i class="icon-thumbs-up"></i>" />
<input name="authenticity_token" type="hidden" value="es4wPqFr9xPBUFsbHQR/gAzofDC+ZwYsiiJ7RAQZUHk=" />
</div></form>

Solution

  • This isn't super sexy, but it works!!

    <%= form_tag({controller:'videos', action:'rate', id: video.hashed_id, yesno:'no', format: 'json'}, {remote:true} ) do %>
    <%= button_tag '', :class=>"rate-btn yes-btn btn btn-default btn-lg glyphicon glyphicon-thumbs-down" %>
    <% end %>
    

    Basically (as mentioned in the comments above), the issue is that the syntax used by glyphicon can't be used on self-closing elements like <input /> so you need a button. Unfortunately Rails's button_to also generates an <input /> (inside of a form). You could write the form by hand with a but you'll run into problems with Rails's built-in forgery prevention system (you need an authenticity token). So instead, I combine the form_tag and the button_tag with corresponding classes and we're good to go.