Sharing HTML between Stimulus and Rails view

I have a controller that needs to be able to insert some HTML into the DOM. The same HTML is rendered in the view by the server.

I enabled support for ERB with Webpacker, but a call to <%= render partial: 'shared/thing' %> doesn’t work. I’ve tried using the full path as well, but no joy. It simply fails to generate the .js file.

If I change it to <%= "test" %> it works fine, so the ERB support is working.

Ideally, I’d like to avoid making a call to the server to get the HTML.

Thanks!

Check out ApplicationController.renderer:

2 Likes

Thanks for the reply. I did look into this, and I can’t get it working. This code doesn’t work:

const html = `<%= ApplicationController.renderer.render template: 'shared/condition' %>`

It’s not a renderer.render error, though, because this works:

const html = `<%= ApplicationController.renderer.render inline: 'something' %>`

The contents of shared/_condition.html.erb isn’t weird, with no variables:

<div data-controller='condition'>
  <a href='#' data-action='condition#remove'><i class="fas fa-trash-alt"></i></a>
  <a href='#' data-toggle="popover" data-target='condition.item' data-action='condition#doNothing'>Item</a>
  <a href='#' data-toggle="popover" data-target='condition.value' data-action='condition#doNothing'>Value</a>
</div>

I’ve tried every combination of path I can think of: app/views/shared/condition, /app/views/shared/condition, with the _, with the .html.erb.

Semi-related: is there somewhere I can see any errors generated? The log shows the compilation succeeded in general, but the controller this is in simply isn’t generated. I can’t find any obvious error log.

Just out of curiosity. Do you use ERB templates in Stimulus controllers at Basecamp?

No, we don’t have any .js.erb files at Basecamp. The majority of our HTML is server-rendered using standard .html.erb templates.

2 Likes

@javan what about rendering HTML where it doesn’t make sense to hold up the UI for a server call? Is there a recommended best practice for something like that?

A good example would be clicking something and placing a marker on it, or showing a popover with a form that may be a new or an edit form in it. These would both be pretty cludgey if they had to wait for a server response.

1 Like