I need to dynamically load a sidebar's content into a sidebar partial based on the presence of a directory name-spaced as the controller_name
(if present) and the action_name
(always used). They both are derived from the Rails hash and map to the .../views/sidebars/[controller_name]/[action_name]
if there is a directory for the controller_name
and to .../views/sidebars/[action_name]
if there isn't an associated directory namespaced with the Controller's name.
/views
/sidebars
/static
/_about.html.erb
/_contact.html.erb
/...
/_styles.html.erb #outside of any controller structure
I am trying to use the following code to dynamically load the correct sidebar partial:
<%= "sidebars/#{controller_name}".to_s.present? ? yield("sidebars/#{controller_name}/#{action_name}" : yield("sidebars/#{action_name}") %>
This checks to see if there is a directory called by the controller_name
and it renders the correct partial based on the structure indicated.
I am getting the following error:
Encountered a syntax error while rendering template: check <div id='sidebar_left'>
<p>Template: [_sidebar-left.html.erb]</p>
<%= render "sidebars/#{action_name}" %>
<%= "sidebars/#{controller_name}".to_s.present? ? yield("sidebars/#{controller_name}/#{action_name}" : yield("sidebars/#{action_name}") %>
UPDATE
Ok so it turns out that ternary operators don't always return the value, particularly if it is a computed string value. In this case, I was expecting the value to return as either sidebars/static/home
or sidebars/styles
. For some reason I can't explain, ternary operators don't work that way, even though I (thought!) I was returning a string value from the operation.
To get rid of the syntax error, I had to assign the operator to a variable name, in this case sb_name
and then render it on the next line. This is the final code:
<% sb_name = "sidebars/#{controller_name}".to_s.present? ? "sidebars/#{controller_name}/#{action_name}" : "sidebars/#{action_name}" %>
<%= render sb_name %>
Now, while this resolved the syntax error, I am now getting a Missing partial sidebars/_about
error in the view. The _styles
file exists as /views/sidebars/_styles.html.erb
, right where it should. Since there is not a folder name-spaced to the controller being called (in this case StylesController
), it should be pulling up the file directly underneath the /sidebars/
directory. However, this is not the case.
CodePudding user response:
I found some help on SO here. I wasn't checking the directory/file structure properly. The final syntax is this:
<% sb_name = File.directory?("app/views/sidebars/#{controller_name}") ? "/sidebars/#{controller_name}/#{action_name}" : "/sidebars/#{action_name}" %>
<%= render partial: "#{sb_name}" %>