I have a problem, I am doing function sharing of templates that is produced in Ruby on Rails. I want to write an API in project A to share a template in "admin/shared/mypage" so that when project B I can call that API to get the template in project A. I've tried sharing and having problems with templates containing html, it works ok, but for patterns with Rails syntax, it's going to crash. Can anyone help me solve this problem. Thank you!
1 Answers
You should be able to use render_to_string
to send the template via the API, then display this response in the view of the project making the request.
For example:
Project B calls project A's API endpoint, passing in the relevant params.
Project A takes these params and loads a template using them, returning this as a string:
def endpoint
# render your erb template, with a `params` (or whatever you need) variable available
render_to_string 'admin/shared/mypage', locals: { params: params }
end
Project B receives this response and assigns it to a variable in the controller:
def your_controller_action
@template = the_response_from_project_a
end
Project B displays this response in the view:
# your_view.html.erb
<%= @template.html_safe %>
There's a little debate on how to display the latter, with a good discussion here if you want to read more.
I've not got a setup available to test this, so a couple of quick points:
- I can't remember whether
render_to_string
requireslocals
or the hash of variables passed directly without this - You might still need to render JSON as your response in the API controller, i.e.
render json: { template: render_to_string...
.
Finally, I'm not sure passing an entire template via the API is ideal - you know your circumstances, but have a think whether there's simpler data you can be passing instead.
Hope this helps - any questions or comments, let me know!

- 11,495
- 5
- 47
- 60
-
Thank you. I answered you with the answer below. You can check it! – Swtiit Jun 12 '18 at 10:44
-
Great, happy to help @Swtiit - if you think this was useful, please feel free to give my answer a tick :) – SRack Jun 12 '18 at 11:32
-
1Yepp! :))))))))))))) – Swtiit Jun 13 '18 at 01:35