Rendering an action (with layout) into a Javascript template

Hi everyone

I have an action:

def index
@settings = Setting.all(:order => ‘name’)

respond_to do |format|
format.html
format.js
end
end

and corresponding views:

index.html.erb:

Settings

...

index.js.erb

$("<%= escape_javascript(render XXX) %>").bigDialog();

So what’s happening is that for HTML requests the HTML template will
be rendered (inside application.html.erb) and for Javascript requests
I want the HTML template to be rendered as a string into the
Javascript snippet so that jQuery can throw out a dialog. The catch is
that dialogs have a separate layout file, dialog.html.erb.

Is there a way to render a template with a layout into my Javascript
snippet where I’ve typed “render XXX”? I’ve looked at render_to_string
but that breaks MVC by taking view material into the controller.

Ideally, I’d like something like render(:action =>
‘index.html.erb’, :layout => ‘dialog’) (note index.html.erb to
distinguish it from index.js.erb) and have this rendered inline.

Ideas?

Thanks!
Tristan

On Mar 1, 3:11 am, Tristan [email protected] wrote:

Is there a way to render a template with a layout into my Javascript
snippet where I’ve typed “render XXX”? I’ve looked at render_to_string
but that breaks MVC by taking view material into the controller.

Ideally, I’d like something like render(:action =>
‘index.html.erb’, :layout => ‘dialog’) (note index.html.erb to
distinguish it from index.js.erb) and have this rendered inline.

I think either render :template, or render :action => …, :format =>
‘html’ would do this

Fred

Thanks for the answer Fred.

After reading the docs for ActionView::Base.render (http://apidock.com/
rails/ActionView/Base/render) I found that ActionView’s render is
quite different to ActionController’s render. Notably, there aren’t
options for :template or :action. However, there is an option
for :file and you can also provide a :layout option which I’ve done:

$("<%= escape_javascript(render(:file => ‘settings/
index.html.erb’, :layout => ‘layouts/dialog’)) %>").bigDialog();

This is works very well but it’s long and not very agile with all
those full paths.

Going to use this for now but I’m going to keep searching for a more
robust solution.

T.

On Mar 2, 1:27 am, Frederick C. [email protected]

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs