Last active
April 15, 2021 23:14
-
-
Save joelmoss/f34e8470fb4fbff3e4b76757a2517457 to your computer and use it in GitHub Desktop.
Side load JS/CSS assets alongside your Rails layout and view
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module SideLoadAssets | |
module_function def append(view, path) | |
identifier = "/#{path}|" | |
path = Rails.root.join(path) | |
path.sub_ext('.js').exist? && view.content_for(:side_loaded_js, identifier) | |
path.sub_ext('.css').exist? && view.content_for(:side_loaded_css, identifier) | |
end | |
module Monkey | |
private def render_template(view, template, layout_name, locals) | |
if template.type == :html | |
if (layout = layout_name && find_layout(layout_name, locals.keys, [formats.first])) | |
SideLoadAssets.append view, "app/views/#{layout.virtual_path}" | |
end | |
SideLoadAssets.append view, "app/views/#{template.virtual_path}" | |
end | |
super | |
end | |
end | |
end | |
ActionView::TemplateRenderer.prepend SideLoadAssets::Monkey |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<title>Side Load Assets</title> | |
<%# Include the side loaded CSS %> | |
<%= stylesheet_link_tag(*content_for(:side_loaded_css)&.split('|')) %> | |
</head> | |
<body> | |
<%= yield %> | |
<%# Include the side loaded JS %> | |
<%= javascript_include_tag(*content_for(:side_loaded_js)&.split('|')) %> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment