Sharing HTML between Stimulus and Rails view


#1

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!


#2

Check out ApplicationController.renderer:


#3

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.


#4

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


#5

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