Lighthouse has a new layout. Prefer the old one? Return to the old layout, and switch back any time from the link at the top of each page.

This project is archived and is in readonly mode.

render_to_string doesn't use :locals option

#1522

The Rails API says of render_to_string "Renders according to the same rules as render, but returns the result in a string instead of sending it as the response body to the browser. "

But this isn't so -- it doesn't use the same rules as render because render accepts the :locals variable, but render_to_string ignores it.

Is there a reason why render_to_string doesn't allow locals or is this an oversight/ bug?

Reported by barunio · December 7th, 2008 @ 03:35 AM

State: invalid
Milestone: 2.x
Assigned to: nobody
Importance: none

Activity

  1. Frederick Cheung
    Frederick Cheung
    • State changed from new to invalid

    I just did a quick experiment and this seemed to work ok (on 2.2.2) . Can you construct a failing test/example to show exactly how it isn't working for you?

    December 7th, 2008 @ 12:59 PM

  2. barunio
    barunio

    i thought maybe there was a change in rails 2.2 that would have made this work, but i just updated to 2.2.2 and this is still not working for me. here is some very simple code to demonstrate:

    I have a ReportsController, with an view in the views/reports/ folder called "show.xml.builder"

    In my controller:

    
    x = render_to_string(:action => 'reports/show.xml.builder', :locals => {:blah => 'hi'})
    

    In the view:

    
    puts blah
    

    I get a "undefined local variable or method blah'" error (because the local variable is never defined for the view).

    December 10th, 2008 @ 09:41 PM

  3. Frederick Cheung
    Frederick Cheung

    :locals only exists for render :partial

    December 10th, 2008 @ 10:01 PM

  4. barunio
    barunio

    actually, locals is accepted when rendering a template as well as a partial - but not for rendering an action, apparently. as reference, from the api docs:

    Renders the template with a local variable

    render :template => "weblog/show", :locals => {:customer => Customer.new}

    i did get render_to_string working with local variables when i render a template, which is fine for my needs. not sure what the logic is behind allowing locals for rendering a template but not an action...

    December 17th, 2008 @ 07:46 AM