Search code examples
ruby-on-railstwitter-bootstrapcontent-for

Setting content_for misunderstanding


I'm using this tutorial to set bootstrap modal content in forms, but I want to set the title...

I think I don't understand how to set the title content_for method...I understand it for templating, but if I want to send a title to the modal, is it best to make a helper for that? Is there a better Rails 4 way to do this?

Please advise, and remember, I'm not a CE--I've looked at the rails doc and google searched, so please don't demean my question by posting a google link. Thanks!


Solution

  • If you're going to be rendering the title of the modal dynamically, it's typically better to use a helper method. This will keep your view logic DRY and readable. This method will accept an argument for the title and if none is present it will render a default title.

    In application_helper.rb:

      def modal_title(title)
        if title.empty?
          "My Default Title"
        else
          title
        end
      end
    

    In your modal partial where the title should appear:

    <%= modal_title(yield(:title)) %>
    

    In the view, you will have access to dynamically set the title using content_for. For example, you could pass a string as your title or pass an instance variable from your controller.

    <% content_for :title, @your_variable %>