Wednesday, May 18, 2022

[FIXED] How to render different versions of the same file?

Issue

For example I have this file:

_goal.html.erb

<table>
  <tr>
    <%= goal.name %>
    <span class="label label-info"><%= goal.deadline.strftime("%d %b %Y") %></span>
  </tr>
</table>

It is being rendered from the home page:

 <h1><b>Goals</b></h1>
   <%= render @unaccomplished_goals %>
   <%= render @accomplished_goals %>
<% end %> 

How can we wrap an accomplished goal with <span class="label label-info-success"> but if it is an unaccomplished goal keep it <span class="label label-info">?

In the controller:

@accomplished_goals = current_user.goals.accomplished
@unaccomplished_goals = current_user.goals.unaccomplished

Here was my latest attempt, which just made them all -info:

<% if @unaccomplished_goals == true %>
  <span class="label label-info"><%= goal.deadline.strftime("%d %b %Y") %></span>
<% else @accomplished_goals == true %>
  <span class="label label-warning"><%= goal.deadline.strftime("%d %b %Y") %></span>
<% end %>

Maybe you'll have more luck :)

Thank you so much.


Solution

Create a helper method that returns the correct classes for the goal's status. In application_helper.rb:

def deadline_label_class(goal)
  if goal.accomplished?
    'label label-info'
  else
    'label label-warning'
  end
end

This assumes that Goal has an instance method called accomplished? which returns true/false. You may have to write that method if it doesn't exist or use some other criteria.

Then use the helper in the _goal.html.erb template:

<table>
  <tr>
    <%= goal.name %>
    <span class="<%= deadline_label_class(goal) %>">
      <%= goal.deadline.strftime("%d %b %Y") %>
    </span>
  </tr>
</table>


Answered By - infused
Answer Checked By - Willingham (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.